Last active
December 6, 2017 21:54
-
-
Save marcoslhc/ee2dba40bc3372ade96ea375b7793cac to your computer and use it in GitHub Desktop.
Simple affix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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