Skip to content

Instantly share code, notes, and snippets.

@Slackwise
Last active July 25, 2016 17:24
Show Gist options
  • Save Slackwise/c4809039e15db0ef7ad7a78f50247294 to your computer and use it in GitHub Desktop.
Save Slackwise/c4809039e15db0ef7ad7a78f50247294 to your computer and use it in GitHub Desktop.
A simple JavaScript function to catch when elements are added to a specified container element.
/**
* A simple function to catch when elements are added to a specified container element.
* @author Most of this code is from a StackOverflow post I can't find right now. I wrapped it into a reusable function.
* @param {HTMLElement} containerElement - The container element to watch for added nodes.
* @param {function} eventHandlerFunction - The function to call when a node is added to the containerElement.
*/
function onDOMInsert(containerElement, eventHandlerFunction) {
if (typeof MutationObserver === 'function') {
var observer = new MutationObserver(function (m) {
for (var i = 0; i < m.length; i++) {
if (m[i].addedNodes.length) {
eventHandlerFunction();
break;
}
}
});
observer.observe(containerElement, {childList: true});
} else if (containerElement.addEventListener) {
containerElement.addEventListener('DOMNodeInserted', eventHandlerFunction);
} else {
containerElement.attachEvent('onDOMNodeInserted', eventHandlerFunction);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment