Skip to content

Instantly share code, notes, and snippets.

@Ayc0
Last active September 19, 2018 07:24
Show Gist options
  • Save Ayc0/db7b1a8171d340b54e13321751330556 to your computer and use it in GitHub Desktop.
Save Ayc0/db7b1a8171d340b54e13321751330556 to your computer and use it in GitHub Desktop.
Detect scroll down
const listeners = { key: 0 }
const handler = (callback) => {
// Init
let y = 0;
let toBottom = false;
return () => {
const scrollY = window.scrollY
if (y < scrollY && !toBottom) {
toBottom = true;
callback(toBottom);
}
if (y > scrollY && toBottom) {
toBottom = false;
callback(toBottom);
}
y = window.scrollY;
}
}
const addListener = callback => {
const fn = handler(callback);
const key = listeners.key;
listeners[key] = fn;
listeners.key++;
window.addEventListener('scroll', fn);
return key;
}
const removeListener = key => {
const fn = listeners[key];
window.removeEventListener('scroll', fn);
delete listeners[key];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment