Skip to content

Instantly share code, notes, and snippets.

@italodr
Created March 13, 2017 15:59
Show Gist options
  • Save italodr/6f1c2b19d4bede377f807937beebbe9d to your computer and use it in GitHub Desktop.
Save italodr/6f1c2b19d4bede377f807937beebbe9d to your computer and use it in GitHub Desktop.
Scroll events
function ScrollEvents() {
let opts = {
element: document.documentElement,
last_scroll_top: 0,
delta_up: 0,
delta_down: 0,
scroll_up_class: 'scroll-up',
scroll_down_class: 'scroll-down'
};
function clearElementClass() {
opts.element.classList.remove(opts.scroll_up_class);
opts.element.classList.remove(opts.scroll_down_class);
}
function onPageScroll(){
let current_scroll_top = this.scrollY || this.scrollTop;
if (current_scroll_top <= 0){
console.log('top of the world');
clearElementClass();
opts.last_scroll_top = current_scroll_top;
} else if(current_scroll_top > opts.last_scroll_top) {
if(Math.abs(opts.last_scroll_top - current_scroll_top) >= opts.delta_down) {
console.log('scrolling down');
if (!opts.element.classList.contains(opts.scroll_down_class)) {
clearElementClass();
opts.element.className += ' ' + opts.scroll_down_class;
}
opts.last_scroll_top = current_scroll_top;
}
} else {
if(Math.abs(opts.last_scroll_top - current_scroll_top) >= opts.delta_up) {
console.log('scrolling up');
if (!opts.element.classList.contains(opts.scroll_up_class)) {
clearElementClass();
opts.element.className += ' ' + opts.scroll_up_class;
}
opts.last_scroll_top = current_scroll_top;
}
}
}
function bindUIActions() {
if (window.addEventListener) {
window.addEventListener('scroll', onPageScroll);
}
}
return {
init: bindUIActions
}
}
export default ScrollEvents();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment