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

ParameterTypeDescription
targetElement
Element[]
NodeList
Window
The element(s) to observe. If Window is passed, it will observe document.body instead.
optionsobjectConfiguration options for the observer

Options

OptionTypeDefaultDescription
callbackfunction-Function called when size changes occur. Receives { entry, entries, observer }
box'content-box'
'border-box'
'device-pixel-content-box'
content-boxThe box model to observe. See MDN for more information

Callback Parameters

When a size change occurs, the callback receives an object with:

PropertyTypeDescription
entryResizeObserverEntryThe current entry being processed
entriesResizeObserverEntry[]All entries being observed
observerResizeObserverThe observer instance

Return Value

Returns an object with the following methods:

MethodParametersDescription
observeElement
Element[]
NodeList
Start observing new elements
unobserveElement
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
})