When elements change size
Unlike the global window.onresize event, the ResizeObserver allows you to watch the dimensions of a SPECIFIC element, regardless of what the main window is doing.
Why is this important?
Imagine a responsive chart or widget. It needs to redraw itself when its container gets too narrow, which can happen even if the browser window size didn't change (e.g., a sidebar was toggled open, shrinking the main content area).
let ro = new ResizeObserver(entries => {
for (let entry of entries) {
console.log('New width of the element:', entry.contentRect.width);
}
});
ro.observe(document.querySelector('textarea'));
Note
ResizeObserver was created to help developers build complex, container-aware UI components before CSS Container Queries became fully supported across all browsers.
Tip
The observer automatically accounts for size changes caused by the sudden appearance of a scrollbar or dynamic content loading inside the element.