Do something when a specific element changes the DOM tree where specified.
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
LICENSE
README.md
nodeListener.1.0.2.min.js
nodeListener.min.js
nodelistener.js
nodelistenerES6.js
nodelistenerES6notify.js
package.json

README.md

nodeListener

React to specific changes in the DOM tree.

This plugin makes use of MutationObserver and is designed to make it much easier for developers to "react to changes in a DOM;" eliminating the need to use performance-hindering intervals or recursive timeouts!

Accepts two parameters: a CSS selector (string - what you're observing - required), and a node (ancestral element - where you're observing it - optional). The second param defaults to document.body, but it's recommended to narrow the observer scope when possible. And in most cases it's best to set this up after your page has rendered.

It incorporates the use of Element.matches() and Element.querySelectorAll(), both native to Javascript. No dependencies.

Methods

  • then : accepts only a callback, which returns both added and removed sets of elements in separate arrays in two arguments; also returns observer context this.

  • on : accepts two parameters: 1. event string (add or remove), and 2. callback, which returns one set of elements as an array; also returns observer context this.

Usage

// example 1
nodeListener('.selector', parentElem).then((added, removed) => {});

// example 2
let myObserver = nodeListener('#selector', parentElem);

myObserver.on('add', addedArray => {
	if (addedArray[0]){
		myObserver.disconnect();	// stop observing / listening
		alert('Element created!');
	}
});

// example 3
nodeListener('#selector').on('remove', function(arr){
	if (arr.length > 0) this.disconnect();
});

Browser Support

This plugin is coded in ES6 Javascript. Version 3 is supported by modern browsers only. For IE support use v1.x; a polyfill for Element.matches() may be required. Please note, v1.x doesn't have the on and then prototypes, but rather accepts a callback as the third parameter.