ResizeObserver
The ResizeObserver interface reports changes to the dimensions of an Element's content or border box, or the bounding box of an SVGElement.
1. The Problem
Before ResizeObserver, detecting when a specific element changed size was difficult. You had to rely on the global window.resize event, which only fires when the viewport changes, not when an element changes size due to layout updates (e.g., a sidebar expanding).
2. Basic Usage
To use it, create a ResizeObserver instance with a callback function, and then observe a target element.
const observer = new ResizeObserver(entries => {
for (let entry of entries) {
const cr = entry.contentRect;
console.log('Element:', entry.target);
console.log(`Element size: ${cr.width}px x ${cr.height}px`);
console.log(`Element padding: ${cr.top}px ; ${cr.left}px`);
}
});
const myElement = document.querySelector('.box');
observer.observe(myElement);
3. The ResizeObserverEntry Object
The callback receives an array of ResizeObserverEntry objects. Key properties include:
contentRect: ADOMRectReadOnlyobject containing the new size of the observed element's content box. This is often what you want for legacy compatibility.borderBoxSize: An array containing the new size of the observed element's border box.contentBoxSize: An array containing the new size of the observed element's content box.devicePixelContentBoxSize: An array containing the size in device pixels (useful for canvas).
const observer = new ResizeObserver(entries => {
for (let entry of entries) {
if (entry.contentBoxSize) {
// Checking for array because older implementations might differ
const contentBoxSize = Array.isArray(entry.contentBoxSize) ? entry.contentBoxSize[0] : entry.contentBoxSize;
console.log(contentBoxSize.inlineSize); // width (in horizontal writing mode)
console.log(contentBoxSize.blockSize); // height
}
}
});
4. Methods
observe(target, options): Starts observing the specifiedElementorSVGElement.options:{ box: 'content-box' | 'border-box' | 'device-pixel-content-box' }
unobserve(target): Ends the observing of a specifiedElementorSVGElement.disconnect(): Unobserves all observed elements of a particular observer.
5. Use Cases
- Responsive Components: Adjusting the layout of a specific component based on its own width, rather than the viewport width (Container Queries logic).
- Canvas Resizing: Resizing a
<canvas>element to match its display size pixel-perfectly.
programming/javascript/vanilla/javascript programming/javascript/vanilla/dom-manipulation programming/javascript/vanilla/intersection-observer programming/javascript/vanilla/mutation-observer