Basic Usage

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

main.js
import { mutationObserver } from '@splendidlabz/utils/dom'

Grab the element you want to listen to, and pass that into mutationObserver. Three properties will be available in the callback:

  • entries — a list of all observed entries
  • entry — the current entry
  • observer — the mutationObserver instance
main.js
const node = document.querySelector('.my-element')
const observer = mutationObserver(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 = mutationObserver(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 mutationObserver. It’ll listen to them all.

main.js
const nodes = document.querySelectorAll('.elements')
const observer = mutationObserver(nodes, {
callback({ entry }) {
// Do something with the resize observer
},
})

Event Listener Pattern

You can also listen for mutationObserver changes via the event listener pattern. Just listen to the mutate event.

main.js
const observer = mutationObserver(node, /* ... */)
node.addEventListener('mutate', ({ detail }) => {
const { entries, entry, observer } = detail
// Do something with the resize observer
})

Observer Options

You can pass in all MutationObserver options to mutationObserver via the second argument.

main.js
const observer = mutationObserver(node, {
callback({ entry }) { /* ... */ },
// Other options go here ...
})

There are seven options in total. All of them default to false.

  • subtree: Monitors the entire subtree of nodes
  • childList: Monitors for addition or removal children elements. If subtree is true, this monitors all descendant elements.
  • attributes: Monitors for a change of attributes
  • attributeFilter: Array of specific attributes to monitor
  • attributeOldValue: Whether to record the previous attribute value if it was changed
  • characterData: Monitors for change in character data
  • characterDataOldValue: Whether to record the previous character data value

Stop Observing Mutations

To stop the mutation observer, use the disconnect method.

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

While disconnecting, mutationObserver will automatically call takeRecords to process any unprocessed mutations.