Skip to content

Instantly share code, notes, and snippets.

@anova
Last active October 7, 2022 11:36
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 anova/9a8f0c6541d711f3b7c6411d375b3ff8 to your computer and use it in GitHub Desktop.
Save anova/9a8f0c6541d711f3b7c6411d375b3ff8 to your computer and use it in GitHub Desktop.
Trigger something when marked element's half percent is visible in viewport.
// define the observer
const observer = new IntersectionObserver((entries) => {
entries.forEach((/** @type IntersectionObserverEntry */ entry) => {
if (entry.isIntersecting) {
const eventIntersecting = new CustomEvent("intersecting");
entry.target.dispatchEvent(eventIntersecting);
return;
}
const eventNotIntersecting = new CustomEvent("not-intersecting");
entry.target.dispatchEvent(eventNotIntersecting);
});
},
{
threshold: 0.5 // if half of the elements in viewport, element is "intersecting"
}
);
const elements = document.querySelectorAll('.element');
elements.forEach((element) => {
//bind each element the observer
observer.observe(element);
element.addEventListener('intersecting', () => {
console.log('intersecting:', element);
});
element.addEventListener('not-intersecting', () => {
console.log('not intersecting:', element);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment