Created
December 22, 2020 06:35
-
-
Save genesisneo/8ca736601022ab0d04ad82b6d17782e6 to your computer and use it in GitHub Desktop.
HTML Scroll Direction Listener
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
// 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