Skip to content
Tutorials Center
My learning

Topics

Lesson 92 of 122 ยท Web APIs

Intersection, Resize and Mutation Observers

Watch elements without polling: IntersectionObserver for lazy reveal and sticky detection, ResizeObserver for size changes, MutationObserver for DOM edits.

Many page features boil down to one question: "tell me when something changes." Is this element on screen yet? Did this box just get narrower? Did a script add a node to my list? The old way was to ask over and over: a scroll handler that measures positions on every pixel of movement, a timer that checks sizes, a loop that scans the DOM. All of that wastes CPU and often makes the page feel janky.

The browser ships three observer APIs that flip the model around. You describe what you care about, and the browser calls your function once the thing happens, at a moment when it is cheap to do so. This lesson covers all three: IntersectionObserver, ResizeObserver and MutationObserver.

The shared pattern

All three observers work the same way:

JavaScript
const observer = new SomeObserver((entries) => {
  for (const entry of entries) {
    // react to each change
  }
});

observer.observe(element);   // start watching
observer.unobserve(element); // stop watching one element
observer.disconnect();       // stop watching everything

The callback receives a list of entries, because several things can change in the same frame. Always loop over the list.

IntersectionObserver: is it visible?

IntersectionObserver reports how much of an element overlaps a viewport, or another ancestor you choose (the root). The entry tells you:

  • isIntersecting: whether any part is inside the root right now
  • intersectionRatio: the visible fraction, from 0 to 1
  • target: the element itself

You create the observer with options:

Option Meaning
root The scrolling container to test against. Omit it (or null) for the browser viewport.
rootMargin Grows or shrinks the root box, like CSS margins: "200px 0px" fires 200 px before the element is visible.
threshold A ratio or a list of ratios (0, 0.5, [0, 0.25, 0.5, 1]) at which to call you.

Reveal on scroll

The classic use: fade items in as they enter the screen, and stop watching them afterwards.

Reveal cards on scroll

Setting threshold: 0.3 means "call me when 30% of a card is visible". Calling unobserve() after the first reveal keeps the observer cheap.

The prefers-reduced-motion rule keeps the content visible and still for people who asked their system for less animation, though the cards here still start hidden until the observer adds the class. Make sure content is never permanently hidden if JavaScript fails: in a real page add the hidden style only when JavaScript is running, for example by setting a class on <html>.

Lazy loading and infinite scroll

The same trick loads things late. Place a small "sentinel" element after your list, observe it, and when it becomes visible fetch the next page. For plain images you usually do not need any script: <img loading="lazy"> does it natively (see Responsive Images). Use IntersectionObserver when you need custom behavior, such as starting a video only while visible.

Detecting a stuck sticky header

CSS position: sticky has no event for "now I am stuck". A one-pixel sentinel solves it: put a tiny element right above the sticky one, and when the sentinel scrolls out of view, the header is stuck.

Detect when a header sticks

ResizeObserver: did the size change?

Media queries react to the window. Sometimes a component needs to react to its own box, for example a chart that must redraw when its container resizes. ResizeObserver fires when an element's content box (or border box) changes size, whatever the cause: window resize, a sidebar opening, a font loading, content being added.

Each entry has contentRect (width and height of the content box) and, in modern browsers, contentBoxSize and borderBoxSize arrays.

Respond to an element's own size

For pure styling, prefer CSS container queries. Use ResizeObserver when JavaScript must act, such as redrawing a canvas or recalculating a virtual list.

Do not change the observed element's size inside the callback in a way that triggers another resize. The browser will report "ResizeObserver loop completed with undelivered notifications" and you can create a feedback loop.

MutationObserver: did the DOM change?

MutationObserver reports changes to the DOM tree: nodes added or removed, attributes changed, text edited. It is how libraries react to content they do not control, and how you can build things like "scroll to the newest chat message" without cooperating code.

You tell observe() which kinds of changes you want:

JavaScript
observer.observe(target, {
  childList: true,      // children added or removed
  attributes: true,     // attribute changes
  characterData: true,  // text node edits
  subtree: true,        // include descendants, not just the target
  attributeFilter: ["class", "hidden"], // optional: only these attributes
});

Each MutationRecord has a type ("childList", "attributes" or "characterData"), the target, and addedNodes / removedNodes for child changes.

Log DOM changes

The log lives outside the observed <ul>, which is deliberate: if you observe a node and your callback modifies that same node, you trigger yourself endlessly. Observe one place, write to another.

Mutation callbacks run as microtasks, right after the script that made the change finishes and before the browser paints. Changes made in one go are batched into one callback with many records. If you need to process the pending records right now, call observer.takeRecords().

Choosing the right observer

You want to know... Use
Is it on screen? How much? IntersectionObserver
Did its width or height change? ResizeObserver
Was DOM or an attribute changed by something else? MutationObserver
Did the tab become hidden? The Page Visibility API (see Page Visibility, Fullscreen and Screen Wake Lock)

Always feature-check older targets with if ("IntersectionObserver" in window), and disconnect observers when a component is removed so they do not hold memory.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is IntersectionObserver better than a scroll event handler for revealing elements?

    The browser computes intersections for you at convenient times, so you avoid running layout-measuring code on every scroll tick.
  2. 2. What does rootMargin "200px 0px" do?

    rootMargin grows or shrinks the root rectangle used for the intersection test, which is how you preload content slightly ahead of time.
  3. 3. Which observer should you use when a chart must redraw because its container got wider after a sidebar opened?

    ResizeObserver reports size changes of an element regardless of why they happened. A window resize event would miss the sidebar case.
  4. 4. What mistake causes an endless loop with MutationObserver?

    If the callback mutates what it observes, that triggers another callback. Write output somewhere that is not observed, or disconnect first.

Summary

  • Observers tell you when something changed, so you do not poll or measure on every scroll or timer tick.
  • IntersectionObserver reports visibility: use threshold and rootMargin for reveal effects, lazy loading, infinite scroll and sticky detection with a sentinel.
  • ResizeObserver reports an element's own size changes: ideal for redrawing canvases and size-dependent logic.
  • MutationObserver reports DOM and attribute changes with childList, attributes, characterData and subtree.
  • Callbacks get a list of entries; use unobserve() and disconnect() to clean up.

Next lesson: History, Location and URL APIs, where JavaScript reads and changes the address bar without reloading the page.