Created
April 30, 2024 18:02
-
-
Save undfine/748154b617c0a522121c3066e5c1c340 to your computer and use it in GitHub Desktop.
JS - Observer for Elements added to the DOM
This file contains hidden or 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
| function observeElementAddedToDOM(elementId, callback) { | |
| // Select the target node | |
| var targetNode = document; | |
| // Options for the observer (which mutations to observe) | |
| var config = { childList: true, subtree: true }; | |
| // Callback function to execute when mutations are observed | |
| var observerCallback = function(mutationsList, observer) { | |
| for(var mutation of mutationsList) { | |
| if (mutation.type === 'childList') { | |
| mutation.addedNodes.forEach(function(node) { | |
| if (node.id === elementId) { | |
| // Execute the callback function when the element is added | |
| callback(); | |
| // Disconnect the observer | |
| observer.disconnect(); | |
| } | |
| }); | |
| } | |
| } | |
| }; | |
| // Create an observer instance linked to the callback function | |
| var observer = new MutationObserver(observerCallback); | |
| // Start observing the target node for configured mutations | |
| observer.observe(targetNode, config); | |
| } | |
| // Example usage: | |
| observeElementAddedToDOM('ELEMENT-ID', function() { | |
| console.log('Element added to the DOM'); | |
| // Your logic here | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment