Skip to content

Instantly share code, notes, and snippets.

@caiotarifa
Last active March 22, 2017 21:16
Show Gist options
  • Save caiotarifa/e21e6935d7b256b222e71d5ff0c7bdd5 to your computer and use it in GitHub Desktop.
Save caiotarifa/e21e6935d7b256b222e71d5ff0c7bdd5 to your computer and use it in GitHub Desktop.
var Sticky = function(selector, containerSelector) {
var element = document.querySelector(selector),
containerElement = document.querySelector(containerSelector),
elementTop = parseInt(window.getComputedStyle(element, null).marginTop),
stickedClass = 'sticked',
grabEndClass = 'grab-end',
elementStart, containerElementFinish;
if (!canSticky) {
return;
}
setPoints();
window.addEventListener('scroll', function() {
if (window.scrollY >= elementStart && window.scrollY < containerElementFinish) {
sticky();
} else if (window.scrollY >= containerElementFinish) {
grabEnd();
} else {
reset();
}
});
// Private
function offset(element) {
var rectangle = element.getBoundingClientRect();
return {
top: rectangle.top + document.body.scrollTop,
left: rectangle.left + document.body.scrollLeft
}
}
function canSticky() {
if (!element && !containerElement) {
return false;
}
if (window.innerHeight <= 710 || window.innerWidth <= 768) {
return false;
}
return true;
}
// Public
function reset() {
element.classList.remove(stickedClass, grabEndClass);
setPoints();
}
function sticky() {
element.classList.remove(grabEndClass);
element.classList.add(stickedClass);
}
function grabEnd() {
element.classList.remove(stickedClass);
element.classList.add(grabEndClass);
}
function setPoints() {
elementStart = offset(element).top - elementTop;
containerElementFinish = offset(containerElement).top + containerElement.offsetHeight - element.offsetHeight - elementTop;
}
return {
reset: reset,
sticky: sticky,
grabEnd: grabEnd,
setPoints: setPoints
};
};
.sticked {
position: fixed;
top: 70px;
}
.grab-end {
position: absolute;
bottom: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment