JavaScript Intermediate Browser APIs · 6 min read

ResizeObserver for Responsive Components

Lesson 29 of 38 in the JavaScript learning path.

How do I react when a card changes width, not the window?

ResizeObserver reports content-box changes for an element you choose.

A window resize listener misses a sidebar that collapses while the window stays the same width.

Syntax & Parameters

Syntax
const observer = new ResizeObserver(entries => {}); observer.observe(card);

Example

Interactive preview available
app.js
const card = document.querySelector("#card");
const label = document.querySelector("#label");
const observer = new ResizeObserver((entries) => {
  const box = entries[0].contentRect;
  const mode = box.width < 240 ? "stack" : "row";
  card.dataset.layout = mode;
  label.textContent = mode + " " + Math.round(box.width) + "px";
});
observer.observe(card);
document.querySelector("#grow").addEventListener("click", () => {
  const next = card.clientWidth + 40;
  card.style.width = next + "px";
});

Expected Output

Clicking grow increases the card width and the label switches from stack to row once the width passes 240.

Line-by-Line Walkthrough

  1. The observer watches the card, not the window.
  2. contentRect.width is the content box width.
  3. Under 240 pixels the card switches to stack.
  4. The label shows the mode and the rounded width.
  5. dataset.layout is a hook for CSS.
  6. The button grows the card to prove the observer fires without a window resize.
  7. observe starts the reports.
  8. Disconnect the observer when the component is removed.

Common Pitfalls & Security

Observers stay alive until you disconnect them.

  • Forgetting disconnect leaks a watcher on a removed card.
  • Writing style inside the callback that changes size can loop.
  • contentRect is not the border box. Borders are extra.
  • A window listener still does not see container changes.

Best Practices & Modern Standards

Observe the component root. Drive layout from data attributes or classes, not from a stream of pixel writes.

Disconnect in the teardown path of a widget.

Real-World Use

A lesson card stacks its thumbnail above the title when a narrow sidebar squeezes it, even if the browser window did not change.

Frequently Asked Questions

How is this different from a media query?

Media queries watch the viewport. ResizeObserver watches one element.

Does it fire immediately?

Yes. You get an initial measurement.

Can it loop?

Yes if the callback changes the size it is watching. Change a class, not the measured width, when you can.

When do I disconnect?

When the element leaves the page.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…