Skip to content

Instantly share code, notes, and snippets.

@ryanscherler
Created January 11, 2019 00:39
Show Gist options
  • Save ryanscherler/3da8e58038d907a626cff90b83ee6f9f to your computer and use it in GitHub Desktop.
Save ryanscherler/3da8e58038d907a626cff90b83ee6f9f to your computer and use it in GitHub Desktop.
Scroll Watcher
/*
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