# Seeing what the observer sees

Source: https://websgeek.com/intersection-observer-rootmargin-threshold
Publisher: WebsGeek (https://websgeek.com), updated 2026-11-25

By the end you will see the exact box an IntersectionObserver measures against, know when each callback fires, and be able to fix the common cases where rootMargin or threshold seem to do nothing.

## What the observer measures

An `IntersectionObserver` calls your function when the visible fraction of an element crosses a threshold you chose. That fraction is measured against the root box, which is the viewport or a scrolling ancestor, grown or shrunk by `rootMargin`. When an observer seems not to work, the root, the margin or the threshold is not what you pictured.

Three terms cover the whole API. The **target** is the element you observe. The **root** is the box it is measured against. The **intersection ratio** is how much of the target's area sits inside the root, from 0 to 1. This guide draws all three on screen so you can watch the observer make its decisions.

> Interactive demo: Scroll the box until the card appears (try it on the page).

Press **Scroll step** a few times, or scroll the box yourself, and read the log. You get one callback shortly after `observe()` is called, even if nothing has moved. You get another when the card first touches the box, and one more when it leaves. Nothing arrives in between, even though the scroll position below changes with every step. The observer reports changes, not positions. The box is also focusable, so you can tab to it and scroll with the arrow keys.

**The smallest useful observer.**

```
const observer = new IntersectionObserver(entries => {
  for (const entry of entries) {
    entry.target.classList.toggle('seen', entry.isIntersecting);
  }
}, {
  root: null,        // null means the viewport
  rootMargin: '0px',
  threshold: 0
});

observer.observe(document.querySelector('.card'));
```

**One level deeper.** Your code never measures anything. While it updates the rendering, the browser runs layout and then computes the intersection of every observed target with its root. If a target has crossed a threshold, the browser queues a task that calls your function with a batch of entries. That is why even the first callback arrives after `observe()` has returned, not during it. Because the geometry is computed after layout, the observer never forces the browser to run layout early.

## Draw the root box

The `rootMargin` option moves the edges of the root before any measuring happens. It uses the same shorthand as CSS `margin`: one to four values, in the order top, right, bottom, left. Positive values grow the box, so a target counts as visible before it reaches the screen. Negative values shrink it.

> Interactive demo: Drag the margin, then scroll (try it on the page).

Push the margin up and the card turns on while it is still hidden below the edge. Pull it negative and the card has to travel well inside the box before anything happens. Then switch to percent. A percentage is resolved against the root's own size, so `10%` is a different distance in a small scroll box than on a large monitor, and it changes when the root resizes. Do not work out percentages in your head; read `rootBounds`.

Negative margins have a surprising edge case. At exactly `-50%`, every side moves in by half the root's size. The root shrinks to a single point at the center of the box, with no area at all. You might expect nothing to intersect a point. The spec says otherwise: a target counts as intersecting when the two rectangles overlap **or are edge-adjacent**, even if the intersection has zero area. So as the card passes the middle of the box, a browser that follows the spec reports `isIntersecting: true` with an `intersectionRatio` of 0. With the default threshold of 0, that change fires a callback.

Do not take that on trust either. Press **-50%** and the demo applies the margin, then scrolls the box from top to bottom in small steps. The third line prints every `isIntersecting` value and ratio your browser reported during the sweep. The first line follows the latest entry. It says the card touches the zero-area root only when your browser reports that, and reports no intersection only when your browser says so. Then press **-60%**. Now the margins add up to more than the root's size. The edges cross, and no rectangle with any area is left. What a browser does with that is not something to assume, so the same sweep runs and prints the result.

Two more rules catch people out. Every value needs a unit, and only `px` and `%` are allowed. The browser also normalizes what you pass, so `observer.rootMargin` reads back as four values. The second row of controls passes your string straight to the constructor and prints what your browser does with it. Press **10** or **2rem** and you see the exception it throws, with its name and message. Press **10px 5%** and you see it expanded to four values, then drawn.

**Draw the rectangle the observer really uses.**

```
const box = document.querySelector('.scroll-box');
const target = box.querySelector('.card');
// an empty div with position: fixed and a dashed border
const outline = document.querySelector('.outline');

const io = new IntersectionObserver(([entry]) => {
  const r = entry.rootBounds; // the root box after rootMargin
  if (!r) return;             // null in cross-origin iframes
  Object.assign(outline.style, {
    left: r.left + 'px', top: r.top + 'px',
    width: r.width + 'px', height: r.height + 'px'
  });
}, { root: box, rootMargin: '40px' });

io.observe(target);
```

> **Cross-origin iframes.** If your script runs inside a cross-origin iframe and uses the default root, the margin is not applied and `rootBounds` is `null`. To use a margin there, pass an element inside the frame as the root.

## Threshold lines

A threshold is a ratio, or a list of ratios, that your callback cares about. The browser calls you each time the target's ratio crosses one of them, in either direction. The default is `0`, which means any contact at all, even an edge touching the root with zero visible area. Values outside 0 to 1 throw a `RangeError`.

> Interactive demo: Set a threshold and scroll across it (try it on the page).

Watch the two numbers. The measured ratio changes with every pixel. The reported one only changes on a crossing, and it rarely equals your threshold exactly, because the browser checks once per rendering update, not once per pixel. Compare with `>=`, never `===`.

Now press **Fling**. It attaches a second observer with the list `[0, 0.25, 0.5, 0.75, 1]`, then moves the box in two consecutive animation frames: first to where the card fills the view, then past it. The card crosses all five thresholds on the way in and all five on the way out. The readout lists the callbacks that actually arrived and the thresholds that never got one of their own. A real flick on a trackpad does the same thing, just less predictably. If your effect needs to see every step, read `intersectionRatio` in the callback you do get instead of counting callbacks.

A list is useful for a stepped effect, but each extra value is one more crossing that wakes your code, so only add the steps you actually use.

**Jump across a target in two frames.**

```
const seen = [];
const io = new IntersectionObserver(es => {
  for (const e of es) seen.push(e.intersectionRatio);
}, { root: box, threshold: [0, 0.25, 0.5, 0.75, 1] });
io.observe(card);

// later, once the first callback has arrived
requestAnimationFrame(() => {
  box.scrollTop = fullyVisibleTop;  // frame 1: ratio 0 to 1
  requestAnimationFrame(() => {
    box.scrollTop = box.scrollHeight; // frame 2: ratio 1 to 0
  });
});
```

## Taller than the root

The ratio divides by the target's own area, not the root's. If the target is taller than the root, the most it can ever show is the root height divided by the target height. A threshold of `1.0` on a hero section, a long article or a full-height panel on a small phone can never be crossed.

> Interactive demo: Scroll both boxes all the way through (try it on the page).

Press **Scroll step** to move both boxes together, or scroll each one yourself. The left card never lights up, however long you leave it in view. You may still get a callback when it starts or stops touching the box, but the ratio inside it never reaches 1. The right card uses a threshold computed from the two heights, so it lights up just as it is about to fill the box.

Here is the arithmetic for this demo. Each box is 170px tall with a 1px border, so the area the observer clips to is 168px high. The card is 280px. The best possible ratio is 168 / 280 = 0.6000. A third observer with 201 thresholds, one every 0.005, watches the left card and the readout prints the highest ratio your browser actually delivered. If that number ever lands below 0.6000, even by a hair, a threshold of exactly 0.6 would never fire. That is the reason for the 0.98 factor: here it gives 0.012 of slack, about 3.4px on this card, against rounding you cannot see. Zoom the page and scroll again, because layout can then snap sizes to device pixels and move the result.

**Fit the threshold to what can actually be visible.**

```
const root = document.querySelector('.panel-list');
const target = root.querySelector('.panel');
// a little under the maximum: ratios use fractional pixels
const fit = Math.min(1, root.clientHeight / target.offsetHeight) * 0.98;

const io = new IntersectionObserver(([entry]) => {
  if (entry.intersectionRatio >= fit) target.classList.add('seen');
}, { root, threshold: [0, fit] });

io.observe(target);
```

Thresholds are fixed when the observer is created. If either size can change, recompute the value and create a new observer, for example from a `ResizeObserver`. Often there is a simpler fix: observe a small marker element at the top or bottom of the long section instead of the section itself.

## The wrong root and the clipping box

Two mistakes make `rootMargin` look ignored. Both are about which box the browser actually measures against.

The first is a root that is not an ancestor of the target. The root has to be above the target in its **containing block chain**, the chain of boxes that position it. If the root is a sibling, or the target is positioned against something outside the root, there is nothing to measure. You get at most one initial entry saying `isIntersecting: false`, then silence.

The second is a scrolling box between the target and the root. The classic case is a lazy-loaded carousel. The root is the viewport with a generous `rootMargin`, but the images sit inside a container with `overflow: auto`. That container clips them first, and the margin only grows the root, not the clip.

> Interactive demo: Scroll both boxes down slowly (try it on the page).

Both observers ask for an 80px bottom margin. On the right, the dashed outline reaches below the box and the card lights up about 80 pixels early. On the left, the margin extends the viewport, but the card is already inside the viewport, just hidden by the box. The box clips it, so it fires right at the edge, as if the margin did not exist. Turn on the sibling switch and the left observer goes quiet for good.

**One level deeper.** To measure a target, the browser starts with the target's border box and walks up the containing block chain toward the root. At every ancestor that clips its overflow, it cuts the rectangle down to that ancestor's visible area. Only at the end does it intersect what is left with the root rectangle and its margin. A margin on the root can never bring back pixels that an inner scroller has already cut away.

There are two fixes. Make the scrolling box the root, as on the right. Or keep the viewport as the root and add `scrollMargin`, which grows the clip of every scroll container along the way. Turn on the first switch to try it; the demo checks whether your browser supports it. `scrollMargin` became Baseline in September 2025, so current versions of Chrome, Edge, Firefox and Safari support it. Older browsers ignore the unknown option, so the observer simply behaves as before.

**Two ways to make the margin reach inside a scroller.**

```
// Keep the viewport as root, grow every scroller on the way
const io = new IntersectionObserver(load, {
  rootMargin: '200px',
  scrollMargin: '200px'
});

// Or measure against the carousel itself
const io2 = new IntersectionObserver(load, {
  root: carousel,
  rootMargin: '0px 200px'
});
```

Now build your own. The panel below turns your choices into a complete constructor for a lazy-loading carousel. Every change also runs the options through the real constructor in your browser, so the last line tells you what it normalized, which thresholds it kept, and whether it knows `scrollMargin`. Copy the code, or copy the prompt and hand it to your coding agent.

> Interactive demo: Build the constructor you tuned (try it on the page).

## What a scroll listener costs

Before `IntersectionObserver` existed, you listened for `scroll` and measured every element with `getBoundingClientRect()`. That still works. The demo runs both approaches on the same 40 rows and times each run with `performance.now()`, so you can see the work in milliseconds, measured on your device.

> Interactive demo: Scroll the list and compare the times (try it on the page).

Press **Scroll the list** or scroll it yourself. While the list moves, the scroll handler runs about once per frame and reads 41 rectangles each time: the box plus every row. The observer calls back only when a row crosses the edge of the box, and it hands you only the rows that changed. The first two lines cover the current second and reset about once a second; the totals keep the difference, along with the slowest single run.

Then turn on **Write a style before each read** and scroll again. Each run now changes a row's padding, reads that row, and repeats, 40 times. This is the read-after-write pattern behind most scroll jank. Watch the average and the slowest run climb compared with read-only mode. The totals reset when you flip the switch, so the two modes are easy to compare. Browsers coarsen `performance.now()` for security, so a single fast run can read as 0.00 ms. Trust the totals and the slowest run more than one line.

**Time a handler and force layout on purpose.**

```
let total = 0, slowest = 0, flip = false;
box.addEventListener('scroll', () => {
  const t0 = performance.now();
  for (const row of rows) {
    row.style.paddingRight = flip ? '15px' : '14px'; // write
    row.getBoundingClientRect();                     // read: forces layout
  }
  flip = !flip;
  const ms = performance.now() - t0;
  total += ms;
  slowest = Math.max(slowest, ms);
}, { passive: true });
```

**One level deeper.** Scroll handlers run on the main thread, which also runs your other scripts, layout and paint. Each `getBoundingClientRect()` call needs up-to-date layout. If anything has changed since the last layout, the read forces the browser to compute layout immediately, in the middle of your script. In write-then-read mode that happens 40 times per run. The observer does its geometry inside the rendering step the browser runs anyway, after layout is done, and only then queues your callback.

The observer is not free either. Its callback time in the readout covers only your code. The browser's own intersection work is not in that number, and every observed target is checked on each rendering update while things move. Observing thousands of elements still costs time. The difference is that the browser does that work natively, once per update, without running your code each time.

**Keep reading:** [when a scroll or resize handler needs debounce or throttle](https://websgeek.com/debounce-vs-throttle)

## Quick answers

**Why is IntersectionObserver rootMargin not working?**
Usually a scrolling container sits between the target and the root. An element with overflow: auto clips the target before the root margin is applied, and rootMargin only grows the root, never that clip. Make the scrolling box the root, or add scrollMargin. Also check that the root is an ancestor of the target and that every margin value has a px or % unit.

**Why does an IntersectionObserver threshold of 1.0 never fire?**
The intersection ratio divides by the target's own area. If the target is taller than the root, the largest ratio it can reach is the root height divided by the target height, so 1.0 is never crossed. Compute a threshold slightly below that maximum, or observe a small marker element at the top or bottom of the long section instead.

**Why doesn't intersectionRatio equal my threshold exactly?**
The browser checks intersections once per rendering update, not on every pixel of scroll. A fast scroll can carry the ratio from 0.1 to 0.8 between two checks, so the reported ratio rarely equals your threshold exactly. Compare with >= instead of ===. A target that passes completely through between two checks may produce no callback at all.

**What units does IntersectionObserver rootMargin accept?**
Only px and %. A unitless value such as '10', or a unit like rem, makes the constructor throw a SyntaxError. Values follow the CSS margin shorthand order: top, right, bottom, left. Percentages resolve against the root's own size, so they change when the root resizes. The observer.rootMargin property always reads back as four normalized values.

**What does IntersectionObserver scrollMargin do?**
scrollMargin grows the clipping rectangle of every scroll container between the target and the root, so a margin can reach inside a carousel or other scroller while the viewport stays the root. It is supported in Chrome and Edge 120, Firefox 141 and Safari 26 and later. Older browsers ignore the unknown option, and the observer behaves as if it were not set.

---
This is the text version of "Seeing what the observer sees" from WebsGeek. The original page has live, interactive demos: https://websgeek.com/intersection-observer-rootmargin-threshold
When you use or quote this, cite: Seeing what the observer sees, WebsGeek, https://websgeek.com/intersection-observer-rootmargin-threshold
