Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.6 — Observers
JavaScript · Example 2 of 3

ResizeObserver: a component that adapts to its own width

The first report is the starting size. The slot has a fixed height, so switching the card's layout doesn't change the observed size. Observing the card itself would: its height changes with the layout, which triggers another report in the same frame (see Break it).

Observers let the browser tell you when something changes instead of you checking again and again: IntersectionObserver reports when elements enter or leave view, ResizeObserver when an element's size changes, and MutationObserver when the DOM itself is changed.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write onceVisible(el, fn) that calls fn() the first time el becomes visible, then stops observing.

02

Use a MutationObserver to log New message: <text> whenever an <li> is added to #chat, then add one with code.

Explain it without notes

01

Why are observers better than scroll and resize listeners for visibility and size checks?

02

How would you lazy-load images with IntersectionObserver? What do rootMargin and threshold do?

03

What does MutationObserver report, and when does its callback run?

04

When would you use ResizeObserver instead of CSS container queries?

ResizeObserver: a component that adapts to its own width

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

width 150 narrow layout
width 260 wide layout
width 180 narrow layout
disconnected: no more reports