Last active
October 4, 2016 13:43
-
-
Save justin-endler/6d0edd08d97e847ccdf6 to your computer and use it in GitHub Desktop.
MutationObserver: Listen Indefinitely On Changing Element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// support multiple browsers | |
// http://stackoverflow.com/questions/2844565/is-there-a-jquery-dom-change-listener/11546242#11546242 | |
MutationObserver = window.MutationObserver || window.WebKitMutationObserver; | |
var elementId = 'some-id'; | |
// instantiate initial observer | |
var observer = new MutationObserver(observeIndefinitely(elementId)); | |
observer.observe(document.getElementById(elementId), { | |
// expensive, only use what's needed of these | |
attributes: true, | |
childList: true, | |
subtree: true, | |
characterData: true | |
}); | |
function observeIndefinitely (id) { | |
return function (mutations, observer) { | |
// do stuff... | |
observer.disconnect(); | |
// re-select the element and set up a subsequent observer | |
var nextObserver = new MutationObserver(observeIndefinitely(id)); | |
nextObserver.observe(document.getElementById(id), { | |
// expensive, only use what's needed of these | |
attributes: true, | |
childList: true, | |
subtree: true, | |
characterData: true | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment