Created
January 11, 2019 00:39
-
-
Save ryanscherler/3da8e58038d907a626cff90b83ee6f9f to your computer and use it in GitHub Desktop.
Scroll Watcher
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
/* | |
Usage: | |
new ScrollWatcher({ | |
selector: '.header--scroll', | |
classes: 'header--scroll-in-view', | |
scrollOffset: 0, | |
}) | |
*/ | |
export default class { | |
constructor( | |
config = { | |
selector: '', | |
classes: 'not-top', | |
scrollOffset: 0, | |
} | |
) { | |
this.selector = config.selector | |
this.classes = config.classes | |
this.scrollOffset = config.scrollOffset | |
this.bindEvents() | |
} | |
bindEvents() { | |
const self = this | |
const selectors = document.querySelectorAll(self.selector) | |
if (selectors) { | |
selectors.forEach(selector => { | |
window.addEventListener( | |
'scroll', | |
function() { | |
if (this.scrollY > self.scrollOffset) { | |
selector.classList.add(self.classes) | |
} else { | |
selector.classList.remove(self.classes) | |
} | |
}, | |
false | |
) | |
}) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment