Skip to content

Instantly share code, notes, and snippets.

@stephenscaff
Created November 4, 2019 22:25
Show Gist options
  • Select an option

  • Save stephenscaff/4df3af72cfec94d2dbfbc3db9672b52d to your computer and use it in GitHub Desktop.

Select an option

Save stephenscaff/4df3af72cfec94d2dbfbc3db9672b52d to your computer and use it in GitHub Desktop.
Detects scroll direction for Header enter and exit animations
/**
* Scroll Direction
* Detects scroll direction for Header enter and exit animations
*/
var ScrollDirection = (function() {
var html = document.querySelector('html');
var appHeader = document.querySelector('.app-header');
var appHeaderHeight = appHeader.clientHeight;
var scrollThrottle = 30;
return {
init: function() {
this.bindEvents();
},
bindEvents: function() {
ScrollDirection.scrollDetect();
},
/**
* Detect scroll direction logic
* Calls subsequent methods
*/
scrollDetect: function() {
var lastScrollTop = 0;
window.addEventListener('scroll', Util.throttle(function() {
var st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop){
ScrollDirection.isScrollingDown();
} else {
ScrollDirection.isScrollingUp();
}
if ( html.classList.contains('is-scrolling-up') && (st <= appHeaderHeight + 100) ) {
ScrollDirection.isCloseToTop();
}
if (st <= 10) {
ScrollDirection.isAtTop();
}
lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}, scrollThrottle), false);
},
/**
* Scrolling Down
*/
isScrollingDown: function() {
// console.log('is scrolling down')
html.classList.remove('is-at-top');
html.classList.remove('is-close-to-top');
html.classList.remove('is-scrolling-up');
html.classList.add('is-scrolling-down');
},
/**
* Scrolling Up
*/
isScrollingUp: function() {
// console.log('is scrolling up')
html.classList.remove('is-scrolling-down');
html.classList.add('is-scrolling-up');
},
/**
* When Close to Top
*/
isCloseToTop: function() {
html.classList.add('is-close-to-top')
},
/**
* Is at top
*/
isAtTop: function() {
html.classList.remove('is-scrolling-down');
html.classList.remove('is-scrolling-up');
html.classList.remove('is-close-to-top');
html.classList.add('is-at-top');
},
}
})();
ScrollDirection.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment