Skip to content

Instantly share code, notes, and snippets.

@joelcardinal
Created March 23, 2018 18:53
Show Gist options
  • Save joelcardinal/840aef1d6f195052ce559054df8a9901 to your computer and use it in GitHub Desktop.
Save joelcardinal/840aef1d6f195052ce559054df8a9901 to your computer and use it in GitHub Desktop.
JavaScript MutationObserver Example
/*
JavaScript MutationObserver
https://caniuse.com/#feat=mutationobserver
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
*/
(function(){
// example initializer
watchElement(document.querySelector('body'),
{
childList : true,
attributes : true,
characterData : true,
subtree : true,
attributeOldValue : false,
characterDataOldValue : false
//attributeFilter : []
},
function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
console.log(mutation);
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
console.log(mutation);
}
}
}
);
// let's do something for the observer to notice
var body = document.querySelector("body"),
newDiv = document.createElement("div");
newDiv.textContent = 'Hello World';
body.appendChild(newDiv);
body.setAttribute('data-testa','a');
// example util
function watchElement(elem,options,callback){
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(elem, options);
// *Later, you can stop observing
//observer.disconnect();
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment