Created
June 4, 2019 02:02
-
-
Save tylerchilds/6ce0bb6e200b3cb797c843dc4ade425b to your computer and use it in GitHub Desktop.
Use requestAnimationFrame to handle scrolling smoothly
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
const createScrollManager = function() { | |
let callbacks = []; | |
let scrollPosition = -1; | |
let animatedKilled = false; | |
const animate = () => { | |
requestAnimationFrame(onScroll); | |
} | |
function onScroll(){ | |
if(animatedKilled) return; | |
if (scrollPosition !== window.pageYOffset) { | |
window.removeEventListener('scroll', animate); | |
scrollPosition = window.pageYOffset; | |
callbacks.forEach(cb => cb(scrollPosition)); | |
animate(); | |
} else { | |
window.addEventListener('scroll', animate); | |
} | |
} | |
animate(); | |
return { | |
add: function(cb) { | |
callbacks = [...callbacks, cb]; | |
}, | |
remove: function(cb) { | |
callbacks = callbacks.filter(value => value != cb); | |
}, | |
destroy: function() { | |
animatedKilled = true; | |
window.removeEventListener('scroll', animate); | |
} | |
} | |
} | |
export default createScrollManager; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would be nice if this could work with resize too, like
scrollManager.add("resize", log1)
andscrollManager.add("scroll", log1)