Resize Observer API
The resizeObserver
function creates a ResizeObserver instance that watches for changes in an element’s size.
const observer = resizeObserver(target, options)
Parameters
Parameter | Type | Description |
---|---|---|
target | Element Element[] NodeList Window | The element(s) to observe. If Window is passed, it will observe document.body instead. |
options | object | Configuration options for the observer |
Options
Option | Type | Default | Description |
---|---|---|---|
callback | function | - | Function called when size changes occur. Receives { entry, entries, observer } |
box | 'content-box' 'border-box' 'device-pixel-content-box' | content-box | The box model to observe. See MDN for more information |
Callback Parameters
When a size change occurs, the callback receives an object with:
Property | Type | Description |
---|---|---|
entry | ResizeObserverEntry | The current entry being processed |
entries | ResizeObserverEntry[] | All entries being observed |
observer | ResizeObserver | The observer instance |
Return Value
Returns an object with the following methods:
Method | Parameters | Description |
---|---|---|
observe | Element Element[] NodeList | Start observing new elements |
unobserve | Element Element[] NodeList | Stop observing an element |
disconnect | () | Stop observing all elements |
destroy | () | Alias for disconnect() |
Event Listener Alternative
If no callback is provided, the observer will dispatch a resize-obs
event on the target element. You can listen for this event:
element.addEventListener('resize-obs', ({ detail }) => { const { entry, entries, observer } = detail // Handle resize})