Skip to content

Instantly share code, notes, and snippets.

@thisbit
Forked from yankiara/scroll-direction.js
Created May 27, 2022 09:32
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 thisbit/bc13bec845f6e0ffe9201dff2671f6d4 to your computer and use it in GitHub Desktop.
Save thisbit/bc13bec845f6e0ffe9201dff2671f6d4 to your computer and use it in GitHub Desktop.
Scroll direction for sticky header/footer, etc.
window.addEventListener( 'DOMContentLoaded', ()=> {
const body = document.body,
scrollUp = "scroll-up",
scrollDown = "scroll-down",
offset = 0;
let lastScroll = window.pageYOffset;
if ( lastScroll > offset ) {
body.classList.add(scrollUp);
}
window.addEventListener('scroll', ()=> {
const currentScroll = window.pageYOffset;
if ( currentScroll <= offset ) {
body.classList.remove(scrollUp);
return;
}
if ( currentScroll > lastScroll && !body.classList.contains(scrollDown) ) {
body.classList.remove(scrollUp);
body.classList.add(scrollDown);
} else if ( currentScroll < lastScroll && !body.classList.contains(scrollUp) ) {
body.classList.remove(scrollDown);
body.classList.add(scrollUp);
}
lastScroll = currentScroll;
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment