Recipe 6.5

Change an Element’s Content Based on Size

You can use a ResizeObserver to detect when an element’s size changes. You can use this event to change the content that is displayed, based on the element’s size.

The element in the demo will display its current width. If you resize your browser window enough that the element’s width changes, the width will be updated on screen.

Demo

Code

JavaScript
// Look up the element you want to observe.
const container = document.querySelector('#resize-container');

// Create a ResizeObserver that will watch the element for size changes.
const observer = new ResizeObserver(entries => {
  // The observer fires immediately, so you can set the initial text.
  // There's typically only going to be one entry in the array - the first element is the element
  // you're interested in.
  container.textContent = `My width is ${entries[0].contentRect.width}px`;
});

// Start watching the element.
observer.observe(container);
HTML
<div class="border p-4" id="resize-container"></div>
Web API Cookbook
Joe Attardi