Skip to content

observeIntersection

Calls callback each time element enters or leaves the viewport (or options.root), with an IntersectionObserver dedicated to it: lazy loading, starting an animation when it becomes visible, pausing a video when it scrolls away. Like IntersectionObserver itself, it is also called once soon after it starts observing.

Without IntersectionObserver, it does nothing and returns a function that does nothing.

Available since v3.1.5

import { observeIntersection } from '@helpers4/browser';
// or, from the all-in-one package (same code, one install):
import { observeIntersection } from 'helpers4/browser';
observeIntersection(element: Element, callback: function, options: ObserveIntersectionOptions): function
ParameterTypeDescription
elementElementThe element to observe
callbackfunctionReceives the `IntersectionObserverEntry` of `element` (`entry.isIntersecting`, `entry.intersectionRatio`, …)
optionsObserveIntersectionOptions`root`, `rootMargin` and `threshold`, as for `IntersectionObserver`, and a `signal` to stop — see ObserveIntersectionOptions

function — A function that stops observing

The callback receives the IntersectionObserverEntry of the element.

const stop = observeIntersection(video, (entry) => (entry.isIntersecting ? video.play() : video.pause()));

Stop observing from the callback after the first load; rootMargin starts loading early.

const stop = observeIntersection(image, (entry) => {
  if (!entry.isIntersecting) return;
  image.src = image.dataset.src!;
  stop();
}, { rootMargin: '200px' });

Options for observeIntersection: those of IntersectionObserver, and a signal.

interface ObserveIntersectionOptions {
  root?: Element | Document | null;
  rootMargin?: string;
  scrollMargin?: string;
  signal?: AbortSignalLike;
  threshold?: number | number[];
}

View source on GitHub