Skip to content

Instantly share code, notes, and snippets.

@Scipion
Created April 12, 2019 07:45
Show Gist options
  • Select an option

  • Save Scipion/f6cdf52b02e6efd04fa78768934c44f3 to your computer and use it in GitHub Desktop.

Select an option

Save Scipion/f6cdf52b02e6efd04fa78768934c44f3 to your computer and use it in GitHub Desktop.
/* MutationObserver*/
function observe(selector){
var targetNodes = document.querySelectorAll(selector);
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
if (mutation.addedNodes.length) {
console.log('A child node has been added.', mutation);
}
else {
console.log('A child node has been removed.', mutation);
}
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.', mutation);
}
}
};
observe['observers']=[];
for(var node of targetNodes) {
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(node, config);
observe['observers'].push(observer);
}
}
observe.stop = function stop() {
for(var obs of observe['observers']) {
obs.disconnect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment