2.0.0 • Published 1 year ago

@georapbox/mutation-observer-element v2.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

npm version npm license

<mutation-observer>

A custom element that offers a declarative interface to the MutationObserver API.

API documentation Demo

Install

$ npm install --save @georapbox/mutation-observer-element

Usage

Script

import { MutationObserverElement } from './node_modules/@georapbox/mutation-observer-element/dist/mutation-observer.js';

// Manually define the element.
MutationObserverElement.defineCustomElement();

Alternatively, you can import the automatically defined custom element.

import './node_modules/@georapbox/mutation-observer-element/dist/mutation-observer-defined.js';

Markup

<mutation-observer 
  attr="*"
  attr-old-value
  char-data
  char-data-old-value
  child-list
>
  <button class="btn-primary">Click to mutate me</button>
</mutation-observer>

API

Properties

NameReflectsTypeDefaultDescription
attrStringnullA string of attribute names to be monitored. To monitor specific attributes' changes, separate them by a space, eg title class href. To monitor all attributes' changes, use *.
attrOldValueattr-old-valueBooleanfalseSet to true to record the previous value of any attribute that changes when monitoring the node or nodes for attribute changes.
childListchild-listBooleanfalseSet to true to monitor the target node for the addition of new child nodes or removal of existing child nodes.
charDatachar-dataBooleanfalseSet to true to monitor the specified target node for changes to the character data contained within the node or nodes.
charDataOldValuechar-data-old-valueBooleanfalseSet to true to record the previous value of a node's text whenever the text changes on nodes being monitored.
disabledBooleanfalseSet to true to stop monitoring for mutations.

All of the above properties reflect their values as HTML attributes to keep the element's DOM representation in sync with its JavaScript state.

NOTE: From the properties above, at least one of attr, child-list or char-data must be present, otherwise, no changes are monitored and no mutation events are emitted.

Slots

NameDescription
(default)The element(s) to observe for mutations.

Events

mutation-observer:mutate - Emitted when the element is mutated. A list of MutationRecord objects is attached to event.detail, with information about how the target element has been changed.

document.querySelector('mutation-observer').addEventListener('mutation-observer:mutate', evt => {
  console.log(evt.detail); // => { mutationList: [MutationRecord] }
});

Changelog

For API updates and breaking changes, check the CHANGELOG.

Browser support

Browsers without native custom element support require a polyfill.

  • Firefox
  • Chrome
  • Microsoft Edge
  • Safari

License

The MIT License (MIT)