Basic Usage
Import the mutationObserver
function from @splendidlabz/utils/dom
.
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 entriesentry
— the current entryobserver
— themutationObserver
instance
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.
const observer = mutationObserver(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 mutationObserver
. It’ll listen to them all.
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.
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.
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 nodeschildList
: Monitors for addition or removal children elements. If subtree is true, this monitors all descendant elements.attributes
: Monitors for a change of attributesattributeFilter
: Array of specific attributes to monitorattributeOldValue
: Whether to record the previous attribute value if it was changedcharacterData
: Monitors for change in character datacharacterDataOldValue
: Whether to record the previous character data value
Stop Observing Mutations
To stop the mutation observer, use the disconnect
method.
const obs = mutationObserver(node, /* ... */)
// Stops listening to all elementsobs.disconnect()
While disconnecting, mutationObserver
will automatically call takeRecords
to process any unprocessed mutations.