Skip to content

Instantly share code, notes, and snippets.

@jptomanelli
Created November 30, 2018 02:09
Show Gist options
  • Save jptomanelli/db42f00551d57dfe79035c9c5bdb4843 to your computer and use it in GitHub Desktop.
Save jptomanelli/db42f00551d57dfe79035c9c5bdb4843 to your computer and use it in GitHub Desktop.
Lightweight IntersectionObserver Wrapper
const scroller = new Scroller();
scroller
.setup({
query: '.box'
})
.onEnter((element, meta) => {
console.log([element, meta]);
})
.onExit((element, meta) => {
console.log([element, meta]);
})
.listen();
/**
* Lightweight IntersectionObserver Wrapper
*/
class Scroller {
constructor() {
this.requiredOptions = ['query'];
this.intersectionObserverOptions = ['root', 'rootMargin', 'threshold'];
this.options = {};
}
onEnterCb() {};
onExitCb() {};
setup(options = {}) {
this.requiredOptions.forEach(opt => {
if (options[opt] == undefined) {
throw Error(`${opt} option is required`);
}
});
this.query = options.query;
this.entries = document.querySelectorAll(this.query);
this.intersectionObserverOptions.forEach(opt => {
if (options[opt]) {
this.options[opt] = options[opt];
}
});
return this;
}
onEnter(cb) {
this.onEnterCb = cb;
return this;
}
onExit(cb) {
this.onExitCb = cb;
return this;
}
listen() {
let ready = false,
previousYOffset = Number.MIN_VALUE;
const handleIntersection = (entries, observer) => {
const direction = window.pageYOffset < previousYOffset ? 'up' : 'down',
meta = {
direction: direction
};
previousYOffset = window.pageYOffset;
entries.forEach(entry => {
if (entry.isIntersecting) {
this.onEnterCb(entry.target, meta);
} else if (ready) {
this.onExitCb(entry.target, meta);
}
});
ready = true;
}
this.io = new IntersectionObserver(handleIntersection, this.options);
this.entries.forEach(entry => {
this.io.observe(entry);
});
return this;
}
destroy() {
this.entries.forEach(entry => {
this.io.unobserve(entry);
});
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment