UNPKG

svelte-intersection-observer

Version:

Detects when an element enters or exits the viewport using the Intersection Observer API.

37 lines (30 loc) 803 B
import { intersectAttachment } from "./intersect.svelte.js"; export function createIntersectionObserver(getOptions = () => ({})) { let intersecting = $state(false); let entry = $state( (null)); const attachment = intersectAttachment(getOptions); function attach(node) { const onObserve = (event) => { const detail = ( event ).detail; entry = detail; intersecting = detail.isIntersecting; }; node.addEventListener("observe", onObserve); const cleanup = attachment(node); return () => { node.removeEventListener("observe", onObserve); if (typeof cleanup === "function") cleanup(); }; } return { get intersecting() { return intersecting; }, get entry() { return entry; }, attach, }; }