Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firing javascript event on every DOM change "complete"

I know this could be handled in some way, but as of now, this is giving me a real hard time. I am writing a script and want to fire some particular functions when a DOM manipulation is complete. I cannot modify/add/remove any other script (as it might be injected into the page using some framework). The page is using ajax requests(not implemented in jQuery) to load/modify content. Now I want an event to be triggered when every DOM modification has been completed. My current approach is to fire the function at every DOMSubtreeModified event. Something like this

$(document).bind('DOMSubtreeModified', doSomeStuff);

But the drawback of this approach is, let say the ajax loads 10 elements in a call, then for each element doSomeStuff is fired. Can this be limited to only firing after the 10th element is loaded? Something like resetting the $(document).ready() event? so $(document).ready() is fired every time the DOM is ready (after loading ajax content)

like image 664
whizzzkid Avatar asked Oct 26 '13 11:10

whizzzkid


People also ask

What happens when the DOM changes?

When you update the DOM, the reflow and repaint happen. Every time the DOM changes, the browser needs to recalculate the CSS, do a layout and repaint the web page. React doesn't really do anything new. It's just a strategic move.

Does DOMContentLoaded wait for scripts?

The DOMContentLoaded event fires when the HTML document has been completely parsed, and all deferred scripts ( <script defer src="…"> and <script type="module"> ) have downloaded and executed. It doesn't wait for other things like images, subframes, and async scripts to finish loading.

How DOM will be used in events in JavaScript?

HTML DOM events allow JavaScript to register different event handlers on elements in an HTML document. Events are normally used in combination with functions, and the function will not be executed before the event occurs (such as when a user clicks a button).


2 Answers

In jQuery, there is a method ajaxComplete, which calls a given function after every finished AJAX call. See more here.

I'd suggest to use jQuery or (in case this is not an option) analyze source code of this function to see how it's done there.

like image 24
Michał Rybak Avatar answered Oct 27 '22 00:10

Michał Rybak


With the Mutation Observer you can listen on changes and if the event is fired the document was changed.

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // Add the actions to be done here if a changes on DOM happened 
    console.log(mutations, observer);

});

// Register the element root you want to look for changes
observer.observe(document, {
  subtree: true,
  attributes: true
});
like image 102
Bernhard Avatar answered Oct 26 '22 22:10

Bernhard