Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

IntersectionObserver: observing element intersections

IntersectionObserver asynchronously reports geometric intersection between an element and a reference region. Learn root, rootMargin, and threshold, and distinguish intersection from actual visibility.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

new IntersectionObserver(callback, { root: null, rootMargin: "0px", threshold: 0 })

IntersectionObserver is a browser Web API, not an ECMAScript feature. Node 24 availability does not establish browser support; check your target environment.

IntersectionObserver root/rootMargin/threshold: root selects the reference region; default null means the viewport. rootMargin expands or shrinks its boundaries using 1–4 pixel or percentage values. These offsets apply only to same-origin-domain targets and are ignored for cross-origin-domain targets. threshold accepts a number or array in [0, 1], defaulting to 0. Read-only thresholds exposes sorted target-area ratios.

After observation starts, the callback normally receives an initial entry for the target, but delivery is not guaranteed. Observation can stop before the entry is generated, and takeRecords() can remove the entry from the queue before it reaches the callback. Later entries are queued for threshold crossings or isIntersecting changes. Geometric intersection does not prove actual visibility; touching edges can yield isIntersecting === true with zero intersection area.

observe(target) starts observation, unobserve(target) stops one target, and disconnect() stops all. The example checks initial full intersection and cleans up.

Examples

(() => {
  if (!("IntersectionObserver" in window)) {
    throw new Error("IntersectionObserver unavailable");
  }
  const root = document.createElement("div");
  root.style.cssText = "position:fixed;top:0;left:0;width:100px;height:100px;overflow:hidden;padding:0;border:0;";
  const target = document.createElement("div");
  target.style.cssText = "width:20px;height:20px;margin:0;";
  root.append(target);
  document.body.append(root);

  const observer = new IntersectionObserver((entries) => {
    console.log(entries[0].intersectionRatio === 1);
    observer.disconnect();
    root.remove();
  }, { root, rootMargin: "0px", threshold: [0, 1] });

  observer.observe(target);
})();

Result

true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources