Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var currentScrollPosY = 0,
- scrollPosY = 1,
- busy = false,
- onTop = true,
- myElement = document.getElementById("MyElement");
- function onScroll() {
- // get current scroll position from window
- currentScrollPosY = window.scrollY;
- // ensure that events don't stack
- if (!busy) {
- // if we were above, and are now below scroll position...
- if (onTop && currentScrollPosY > scrollPosY) {
- // suspend accepting scroll events
- busy = true;
- // remember that we are below scroll position
- onTop = false;
- // asynchronuously add style / class to element
- requestAnimationFrame(belowScrollPos);
- // if we were below, and are now above scroll position...
- } else if (!onTop && currentScrollPosY <= scrollPosY) {
- // suspend accepting scroll events
- busy = true;
- // remember that we are above scroll position
- onTop = true;
- // asynchronuously add style / class to element
- requestAnimationFrame(aboveScrollPos);
- }
- }
- };
- function aboveScrollPos() {
- // add style / class to element
- myElement.classList.add("aboveScrollPos");
- myElement.classList.remove("belowScrollPos");
- // resume accepting scroll events
- busy = false;
- };
- function belowScrollPos() {
- // add style / class to element
- myElement.classList.add("belowScrollPos");
- myElement.classList.remove("aboveScrollPos");
- // resume accepting scroll events
- busy = false;
- };
- // register for window scroll events
- window.addEventListener('scroll', onScroll, false);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement