Skip to content

Instantly share code, notes, and snippets.

@marcoslhc
Last active December 6, 2017 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcoslhc/ee2dba40bc3372ade96ea375b7793cac to your computer and use it in GitHub Desktop.
Save marcoslhc/ee2dba40bc3372ade96ea375b7793cac to your computer and use it in GitHub Desktop.
Simple affix
var lastKnownScroll = 0;
var ticking = false;
var getPaddingTop = function(elm) {
return Number(
window
.getComputedStyle(elm)
.getPropertyValue("padding-top")
.slice(0, -2)
);
};
var getScrollLimit = function(elm) {
return elm.getClientRects()[0].top - getPaddingTop(elm) - elm.offsetHeight;
};
var rAF = function(fn) {
if (!ticking) {
requestAnimationFrame(fn);
}
ticking = true;
};
var stickOnScroll = function(elm) {
var limit = getScrollLimit(elm);
return function() {
var currentScroll = lastKnownScroll;
if (currentScroll > limit) {
elm.classList.add("fixed");
} else {
elm.classList.remove("fixed");
}
ticking = false;
};
};
document.addEventListener("DOMContentLoaded", function() {
var elm = document.querySelector("[data-affix]");
var scrollFn = stickOnScroll(elm);
window.addEventListener("scroll", function() {
lastKnownScroll = window.pageYOffset;
rAF(scrollFn);
});
rAF(scrollFn);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment