A framework-agnostic utility that observes when a DOM element enters or leaves the viewport (or a scrollable container) using the IntersectionObserver API.
When the element enters view, onStart is called. If onStart returns a function, that function is called when the element leaves. Returns a cleanup function that disconnects the observer.
Use useInView instead when working inside React components.
1import { inView } from "@ngrok/mantle/utils";1import { inView } from "@ngrok/mantle/utils";2 3const element = document.querySelector(".my-element");4 5const stop = inView(element, (el) => {6 el.classList.add("visible");7 return () => el.classList.remove("visible");8});9 10// Later, stop observing:11stop();If onStart returns nothing (undefined or void), the observer automatically unobserves the element after the first entry — useful for one-shot entrance animations:
1import { inView } from "@ngrok/mantle/utils";2 3const element = document.querySelector(".fade-in");4 5inView(element, (el) => {6 el.classList.add("animate");7 // No return value → stops observing after first entry8});1import { inView } from "@ngrok/mantle/utils";2 3// Trigger only when 50% of the element is visible4inView(5 element,6 (el) => {7 el.classList.add("half-visible");8 return () => el.classList.remove("half-visible");9 },10 { amount: 0.5 },11);1import { inView } from "@ngrok/mantle/utils";2 3const container = document.querySelector(".scroll-container");4 5inView(6 element,7 (el) => {8 el.classList.add("in-view");9 return () => el.classList.remove("in-view");10 },11 { root: container },12);1function inView(2 element: Element,3 onStart: (element: Element, entry: IntersectionObserverEntry) => void | ViewChangeHandler,4 options?: InViewOptions,5): VoidFunction;Returns a VoidFunction that unobserves the element and disconnects the observer when called.