Skip to content

Instantly share code, notes, and snippets.

@markhowellsmead
Created August 10, 2021 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markhowellsmead/84014d5a3dd8b2c0a12c82f1a303d304 to your computer and use it in GitHub Desktop.
Save markhowellsmead/84014d5a3dd8b2c0a12c82f1a303d304 to your computer and use it in GitHub Desktop.
IntersectionObserver example
/**
* Example code for a scrolling IntersectionObserver
* Original by Keith Devon https://highrise.digital/blog/animating-blocks-on-scroll-with-intersection-observer/
*
*/
document.addEventListener('DOMContentLoaded', () => {
// get all the scroll-group elemetns.
const scrollGroups = document.querySelectorAll('[class*="scroll-group"]');
// for each scroll-group element.
scrollGroups.forEach(el => {
// create an array from the element classes.
let elClasses = el.className.split(' ');
// for each of the classes in the array.
for (let index in elClasses) {
// if the class contains the 'scroll-group-' string.
if (elClasses[index].match(/^scroll-group-/)) {
// get the string that follows after the '--' split.
let targetClassName = elClasses[index].split('--')[1];
// get the children of the element that have the target classname.
let children = el.querySelectorAll('.' + targetClassName);
// for each of the children with the target classname.
children.forEach(el => {
// add the 'scroll' class.
el.classList.add('scroll');
});
break;
}
}
});
// get all of the elements with the 'scroll' class.
const scrollList = document.querySelectorAll('.scroll, [class*="scroll-group"]');
const callback = entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('scrolled-in');
}
});
};
const myObserver = new IntersectionObserver(callback);
scrollList.forEach(scrollItem => {
myObserver.observe(scrollItem);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment