Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

IntersectionObserver options: root, rootMargin, and threshold

Choose the reference area with `root`, adjust its bounds for the calculation with `rootMargin`, and use `threshold` to specify which fractions of the target’s area trigger notifications.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

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

The IntersectionObserver root/rootMargin/threshold options configure a browser Web API, not an ECMAScript feature. root chooses the reference area: omit it or pass null to use the top-level document’s viewport. An explicit root can be a Document or an Element, such as a scroll container. With an element root, the target must be its descendant in the layout’s containing-block chain.

rootMargin is a string of one to four CSS absolute lengths or percentages expanded like CSS margin: top, right, bottom, left. The specification converts absolute lengths such as cm to pixels during parsing. For browser compatibility, use px or %, since some implementations reject other absolute units. Each side defaults to 0px. Percentages are relative to the width of the undilated root rectangle, even for top and bottom. Positive offsets expand the rectangle used for the calculation; negative offsets shrink it. This does not change layout or undo clipping by intervening ancestors. For cross-origin targets, the margin is ignored and entry.rootBounds is null.

threshold accepts one number or an array of numbers from 0 to 1 inclusive. Omission or an empty array gives a threshold of 0. The constructor option is threshold, singular; the read-only observer.thresholds property returns a numerically sorted array. An out-of-range threshold throws a RangeError; an invalid rootMargin throws a DOMException named SyntaxError.

After observe(target), the callback asynchronously receives an initial entry even if the target does not intersect. Further entries are queued when a threshold is crossed in either direction or entry.isIntersecting changes, not on every ratio change. 0.5 means half the target’s bounding-box area, not half the root’s area. Edge contact can give isIntersecting: true with intersectionRatio: 0. For a zero-area target box, the ratio is 1 if isIntersecting is true and 0 otherwise. Geometric intersection does not prove the user can see the target.

The options are fixed at construction. To change them, create a new observer. Use unobserve(target) to stop watching one target or disconnect() to stop watching them all. Check support in the environment where the code will run.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>IntersectionObserver options</title>
</head>
<body>
<script>
{
  const root = document.createElement("div");
  const spacer = document.createElement("div");
  const target = document.createElement("div");
  root.style.cssText = "width: 120px; height: 100px; overflow: hidden";
  spacer.style.height = "120px";
  target.style.cssText = "height: 40px; background: teal";
  root.append(spacer, target);
  document.body.append(root);

  const observer = new IntersectionObserver(([entry], observer) => {
    console.log(`root matches: ${observer.root === root}`);
    console.log(`rootMargin: ${observer.rootMargin}`);
    console.log(`thresholds: ${JSON.stringify(observer.thresholds)}`);
    console.log(`isIntersecting: ${entry.isIntersecting}`);
    console.log(`intersectionRatio: ${entry.intersectionRatio}`);
    observer.disconnect();
    root.remove();
  }, {
    root,
    rootMargin: "0px 0px 40px",
    threshold: [1, 0, 0.5],
  });
  observer.observe(target);
}
</script>
</body>
</html>

Result

root matches: true
rootMargin: 0px 0px 40px 0px
thresholds: [0,0.5,1]
isIntersecting: true
intersectionRatio: 0.5

Save the example as an HTML file, open it in an active browser tab, and check the developer console for the output. The target starts 20 px below the root’s bottom edge. The 40 px bottom margin includes half the target’s height across its full width, so the initial entry reports `intersectionRatio: 0.5`. The code disconnects the observer and removes the demo elements.

Related lessons

  • JavaScript · Lesson 30 · Intermediate · Version: 3

Sources