Last active
October 7, 2022 11:36
-
-
Save anova/9a8f0c6541d711f3b7c6411d375b3ff8 to your computer and use it in GitHub Desktop.
Trigger something when marked element's half percent is visible in viewport.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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