Skip to content

Instantly share code, notes, and snippets.

@genesisneo
Created December 22, 2020 06:35
Show Gist options
  • Save genesisneo/8ca736601022ab0d04ad82b6d17782e6 to your computer and use it in GitHub Desktop.
Save genesisneo/8ca736601022ab0d04ad82b6d17782e6 to your computer and use it in GitHub Desktop.
HTML Scroll Direction Listener
// compatibility check
const supportPageOffset = window.pageXOffset !== undefined;
const isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat');
// previous scroll value
let currentScrollTop = supportPageOffset
? window.pageYOffset
: isCSS1Compat
? document.documentElement.scrollTop
: document.body.scrollTop;
// timeout variable
let isScrolling;
function scrollDirectionListener (event) {
// current scroll value
const newScrollTop = supportPageOffset
? window.pageYOffset
: isCSS1Compat
? document.documentElement.scrollTop
: document.body.scrollTop;
// get scroll direction
const direction = newScrollTop > currentScrollTop
? 'Scrolling down.'
: 'Scrolling up.';
console.log('direction:', direction)
currentScrollTop = newScrollTop;
// clear our timeout throughout the scroll
window.clearTimeout(isScrolling);
// set a timeout to run after scrolling ends
isScrolling = setTimeout(function() {
console.log('Scrolling has stopped.');
}, 128);
}
document.addEventListener('scroll', scrollDirectionListener);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment