Skip to content

Instantly share code, notes, and snippets.

@davej
Last active September 12, 2016 21:04
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 davej/bae0099e2a305ef12de52137f761df56 to your computer and use it in GitHub Desktop.
Save davej/bae0099e2a305ef12de52137f761df56 to your computer and use it in GitHub Desktop.
Performant scroll change listener
// Your scroll callback will only be called once per frame and only
// when the y-position changes. Good for doing DOM work without causing
// unnecessary reflows of the document.
function onScrollYChange(callback) {
let latestKnownScrollY = 0, ticking = false;
const scrollChanged = () => {
ticking = false;
const currentScrollY = latestKnownScrollY;
callback(currentScrollY)
}
const requestTick = () => {
if (!ticking) requestAnimationFrame(scrollChanged);
ticking = true;
}
const scrollListener = () => {
latestKnownScrollY = window.scrollY;
requestTick();
}
window.addEventListener('scroll', scrollListener, false);
}
// Usage
onScrollYChange(yPos => {
console.log(yPos)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment