CodeBlanks Logo Icon CodeBlanks

ResizeObserver

JavaScript course · Advanced · Lesson 92/100

Learn to observe an element's size changes with ResizeObserver.

ResizeObserver

ResizeObserver tells you when an element's size changes. People used to listen to window.addEventListener('resize', ...), but that only fires when the window resizes, not when an element shrinks on its own. ResizeObserver watches each element individually.

You create it with new ResizeObserver(callback). The callback receives an entries array; each entry exposes contentRect or borderBoxSize. Add an element with observe.

contentRect and borderBoxSize

The callback receives a ResizeObserverEntry for each element. Two main fields:

  • contentRect: the content box position and size; width and height are most used
  • borderBoxSize: size including border; arrives as an array in new browsers

Older browsers only have contentRect. In new code, using both is a good habit.

Cleanup with disconnect

When you are done, calling observer.disconnect() stops watching and frees memory. If you skip it, the observer can hold a reference to an element even after it is removed, blocking the garbage collector.

In single page apps, calling disconnect when a component unmounts is an important habit. You can reuse one observer for many elements and stop them all with one call.

Exercise Watch the box width

Create a ResizeObserver. The callback takes an entries array; for each entry, log entry.contentRect.width. Finally start with observer.observe(box).

Show example solution
1. Create with new ResizeObserver((entries) => {...}).
2. For each entry, log entry.contentRect.width.
3. Start with observer.observe(box).

Example solution:
const observer = new ResizeObserver((entries) => {
  for (const entry of entries) {
    console.log(entry.contentRect.width);
  }
});
observer.observe(box);

Test yourself

  1. What advantage does ResizeObserver have over the window resize event?

    • It needs less code
    • It catches individual element size changes
    • It only watches the window
    • It never fires
    Show answer

    It catches individual element size changes — Correct. ResizeObserver watches each element; it fires even when the element shrinks, not the window.

  2. Read the width

    for (const entry of entries) {
      const w = entry.contentRect.____;
    }
    Show answer
    for (const entry of entries) {
      const w = entry.contentRect.width;
    }
  3. Match ResizeObserver terms

    contentRect
    Content box size
    borderBoxSize
    Border-inclusive size
    observe
    Start watching
    disconnect
    Stop watching

All lessons in Advanced