Skip to content

Instantly share code, notes, and snippets.

@LiamChapman
Created March 12, 2019 15:17
Show Gist options
  • Select an option

  • Save LiamChapman/0f7c134ecadd0249e45511d2a85d7f8e to your computer and use it in GitHub Desktop.

Select an option

Save LiamChapman/0f7c134ecadd0249e45511d2a85d7f8e to your computer and use it in GitHub Desktop.
Intersection Observer Helper Function
// Polyfill
if (typeof window !== 'undefined') {
require('intersection-observer'); // eslint-disable-line global-require
}
// when elements intersect add css class
export default ({
elements,
threshold,
root = null,
rootMargin = '0px',
}) => {
const options = {
root,
rootMargin,
threshold,
};
const observer = new IntersectionObserver((entries) => {
for (let x = 0; x < entries.length; x += 1) {
const entry = entries[x];
if (entry.isIntersecting) entry.target.classList.add(entry.target.dataset.classToAdd);
}
}, options);
for (let i = 0; i < elements.length; i += 1) {
observer.observe(elements[i]);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment