Created
March 13, 2017 15:59
-
-
Save italodr/6f1c2b19d4bede377f807937beebbe9d to your computer and use it in GitHub Desktop.
Scroll events
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
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