Mutation Observer
mutationObserver
gives you an incredibly simple way to use the Mutation Observer API — so much that you’ll probably wanna ditch the original API for good.
Super simple way to use Mutation Observer
Instead of writing the standard MutationObserver
boilerplate, just use our utility function.
It can’t get simpler than doing the stuff you want inside a standard callback
!
const node = document.querySelector('.my-element')const obs = mutationObserver(node, { callback({ entry }) { // Do something with the mutation observer },})
Listen to multiple elements at once
Grab the elements — either as an array or nodelist — and pass them to mutationObserver
. It’ll listen to them without complains.
const nodes = document.querySelectorAll('.elements')const obs = mutationObserver(nodes, { callback({ entry }) { // Do something with the mutation observer },})
Automatically take records before disconnecting
Mutation Observer has a takeRecords
method that lets you process unprocessed mutations before disconnecting.
We’ve built that directly into the disconnect
method so you never have to worry about taking records manually.
const obs = mutationObserver(node, /* ... */)
// Stops listening.// No need to call `takeRecords` manually!obs.disconnect()
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.
Please purchase a license to view this content
This content is part of our premium documentation. To access it, you'll need to have an active license for one of these products.
If you already have a license, please login to access this content.
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.
Mutation Observer API
The mutationObserver
function creates a MutationObserver
instance that watches for changes in the DOM tree.
const observer = mutationObserver(target, options)
Parameters
Parameter | Type | Description |
---|---|---|
target | Element Element[] NodeList Window | The element(s) to observe. If Window is passed, it will observe document.body instead. |
options | object | Configuration options for the observer |
Options
Option | Type | Default | Description |
---|---|---|---|
callback | function | - | Function called when mutations occur. Receives { entry, entries, observer } |
attributes | boolean | false | Whether to observe attribute changes |
childList | boolean | false | Whether to observe changes to the target’s children |
subtree | boolean | false | Whether to observe changes to the target’s descendants |
attributeFilter | string[] | - | Array of attribute names to observe. Only used if attributes is true |
attributeOldValue | boolean | false | Whether to record the previous value of attributes |
characterData | boolean | false | Whether to observe changes to the target’s data |
characterDataOldValue | boolean | false | Whether to record the previous value of character data |
For more details about these options, see the MDN documentation.
Callback Parameters
When a mutation occurs, the callback receives an object with:
Property | Type | Description |
---|---|---|
entry | MutationRecord | The current mutation record being processed |
entries | MutationRecord[] | All mutation records being observed |
observer | MutationObserver | The observer instance |
Return Value
Returns an object with the following methods:
Method | Parameters | Return Value | Description |
---|---|---|---|
observe | Element Element[] NodeList | - | Starts observing new elements for mutations |
takeRecords | - | MutationRecord[] | Returns all pending mutation records and clears the queue |
disconnect | - | - | Stops observing all elements, processes any pending records through the callback, and then disconnects the observer |
destroy | - | - | Alias for disconnect() . |
Event Listener Alternative
If no callback is provided, the observer will dispatch a mutate
event on the target element. You can listen for this event:
element.addEventListener('mutate', ({ detail }) => { const { entry, entries, observer } = detail // Handle mutation})
Please purchase a license to view this content
This content is part of our premium documentation. To access it, you'll need to have an active license for one of these products.
If you already have a license, please login to access this content.
Mutation Observer API
The mutationObserver
function creates a MutationObserver
instance that watches for changes in the DOM tree.
const observer = mutationObserver(target, options)
Parameters
Parameter | Type | Description |
---|---|---|
target | Element Element[] NodeList Window | The element(s) to observe. If Window is passed, it will observe document.body instead. |
options | object | Configuration options for the observer |
Options
Option | Type | Default | Description |
---|---|---|---|
callback | function | - | Function called when mutations occur. Receives { entry, entries, observer } |
attributes | boolean | false | Whether to observe attribute changes |
childList | boolean | false | Whether to observe changes to the target’s children |
subtree | boolean | false | Whether to observe changes to the target’s descendants |
attributeFilter | string[] | - | Array of attribute names to observe. Only used if attributes is true |
attributeOldValue | boolean | false | Whether to record the previous value of attributes |
characterData | boolean | false | Whether to observe changes to the target’s data |
characterDataOldValue | boolean | false | Whether to record the previous value of character data |
For more details about these options, see the MDN documentation.
Callback Parameters
When a mutation occurs, the callback receives an object with:
Property | Type | Description |
---|---|---|
entry | MutationRecord | The current mutation record being processed |
entries | MutationRecord[] | All mutation records being observed |
observer | MutationObserver | The observer instance |
Return Value
Returns an object with the following methods:
Method | Parameters | Return Value | Description |
---|---|---|---|
observe | Element Element[] NodeList | - | Starts observing new elements for mutations |
takeRecords | - | MutationRecord[] | Returns all pending mutation records and clears the queue |
disconnect | - | - | Stops observing all elements, processes any pending records through the callback, and then disconnects the observer |
destroy | - | - | Alias for disconnect() . |
Event Listener Alternative
If no callback is provided, the observer will dispatch a mutate
event on the target element. You can listen for this event:
element.addEventListener('mutate', ({ detail }) => { const { entry, entries, observer } = detail // Handle mutation})