Created
November 19, 2025 10:09
-
-
Save canxerian/2ed2ea9bb5292e941dbda7b2ee764cc7 to your computer and use it in GitHub Desktop.
onIntersect - a JS function that detects when an element is visible in the viewport and triggers a callback
This file contains hidden or 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
| /** | |
| * A helper to run a callback when an element is intersecting the viewport | |
| * | |
| * @param element Element | |
| * @param threshold How much of the vertical height of the element in viewport before callback is triggered | |
| * @param callback The callback on intersect | |
| * @returns | |
| */ | |
| export function onIntersect(element: Element, threshold: number, callback: () => void) { | |
| if (!element) { | |
| console.error("onIntersect: element is null or undefined"); | |
| return; | |
| } | |
| const observer = new IntersectionObserver( | |
| (entries) => { | |
| entries.forEach((entry) => { | |
| if (entry.isIntersecting) { | |
| callback(); | |
| observer.unobserve(entry.target); | |
| } | |
| }); | |
| }, | |
| { | |
| threshold, | |
| }, | |
| ); | |
| observer.observe(element); | |
| } | |
| // Example usage: | |
| const myElement = document.getElementById("my-element") as Element; | |
| onIntersect(myElement, 0.5, () => { | |
| // Add some class to trigger animation | |
| myElement.classList.add("visible"); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment