Created
May 17, 2019 09:26
-
-
Save adamfaux85/1fa5cead6399997b2fe4b5ed9e772d4d to your computer and use it in GitHub Desktop.
Vanilla JS: Scrolling up or down
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
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