Skip to content

Instantly share code, notes, and snippets.

@adamfaux85
Created May 17, 2019 09:26
Show Gist options
  • Save adamfaux85/1fa5cead6399997b2fe4b5ed9e772d4d to your computer and use it in GitHub Desktop.
Save adamfaux85/1fa5cead6399997b2fe4b5ed9e772d4d to your computer and use it in GitHub Desktop.
Vanilla JS: Scrolling up or down
let scrollPos = 0;
const Elem = document.querySelector('.element');
function checkPosition() {
let windowY = window.scrollY;
if (windowY < scrollPos) {
// Scrolling UP
Elem.classList.add('is-visible');
Elem.classList.remove('is-hidden');
} else {
// Scrolling DOWN
Elem.classList.add('is-hidden');
Elem.classList.remove('is-visible');
}
scrollPos = windowY;
}
function debounce(func, wait = 10, immediate = true) {
let timeout;
return function() {
let context = this, args = arguments;
let later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
let callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
window.addEventListener('scroll', debounce(checkPosition));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment