Basic Usage

Import the resizeObserver function from @splendidlabz/utils/dom.

main.js
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 entries
  • entry — the current entry
  • observer — the resizeObserver instance
main.js
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.

main.js
const observer = resizeObserver(node, /* ... */)
// Observe additional elements
const 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.

main.js
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.

main.js
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.

main.js
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.

main.js
const obs = resizeObserver(node, /* ... */)
// Stops listening to the element
obs.unobserve(node)

To stop observing all elements, use the disconnect method.

main.js
const obs = resizeObserver(node, /* ... */)
// Stops listening to all elements
obs.disconnect()