Basic Usage
Import the resizeObserver
function from @splendidlabz/utils/dom
.
import { resizeObserver } from '@splendidlabz/utils/dom'
Grab the element you want to listen to, and pass that into resizeObserver
. Three properties will be available in the callback:
entries
— a list of all observed entriesentry
— the current entryobserver
— theresizeObserver
instance
const node = document.querySelector('.my-element')const observer = resizeObserver(node, { callback({ entries, entry, observer }) { // Do something with the resize observer },})
Observing additional elements
You can observe additional elements after the initial setup with the observe
method.
const observer = resizeObserver(node, /* ... */)
// Observe additional elementsconst node2 = document.querySelector('.my-element-2')observer.observe(node2)
Listening to multiple elements
Grab the elements you want to listen to — either as an array or nodelist — and pass them to resizeObserver
. It’ll listen to them all.
const nodes = document.querySelectorAll('.elements')const observer = resizeObserver(nodes, { callback({ entry }) { // Do something with the resize observer },})
Event Listener Pattern
You can also listen for resizeObserver
changes via the event listener pattern. Just listen to the resize-obs
event.
const observer = resizeObserver(node, /* ... */)
node.addEventListener('resize-obs', ({ detail }) => { const { entries, entry, observer } = detail // Do something with the resize observer})
Observer Options
You can pass in all ResizeObserver
options to resizeObserver
via the second argument.
const observer = resizeObserver(node, { callback({ entry }) { /* ... */ }, // Other options go here ...})
The only option is box
— which determines the box model for the Resize Observer will use.
Stop Observing Elements
To stop observing an element, use the unobserve
method.
const obs = resizeObserver(node, /* ... */)
// Stops listening to the elementobs.unobserve(node)
To stop observing all elements, use the disconnect
method.
const obs = resizeObserver(node, /* ... */)
// Stops listening to all elementsobs.disconnect()