Skip to content

Instantly share code, notes, and snippets.

@MogulChris
Created October 22, 2020 02:28
Show Gist options
  • Save MogulChris/68d3ae1dc9410605c70cff9335b97ab9 to your computer and use it in GitHub Desktop.
Save MogulChris/68d3ae1dc9410605c70cff9335b97ab9 to your computer and use it in GitHub Desktop.
Watching for changes to a DOM node
//See https://www.smashingmagazine.com/2019/04/mutationobserver-api-guide/
var target = document.querySelector('#wrap'); //the parent element you wish to watch
var my_callback_done = false; //flag to avoid running our callback repeatedly
// 1. Create an observer instance
var observer = new MutationObserver(function(mutations) {
if(my_callback_done) return;
//Do things here
console.log('Running callback')
my_callback_done = true;
});
// 2. Configuration of the observer. In this case, watch for new or removed elements anywhere inside our target
var config = { subtree: true, childList: true };
// 3. Start the observer
observer.observe(target, config);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment