jQuery function after .append

How to call a function after jQuery .append is completely done?

Here's an example:

$("#root").append(child, function(){
   // Action after append is completly done
});

The issue: When a complex DOM structure is appended, calculation of new size of the root element within the append function callback is wrong. Assumptions are that the DOM in still not completely loaded, only the first child of the added complex DOM is.


Solution 1:

You've got many valid answers in here but none of them really tells you why it works as it does.

In JavaScript commands are executed one at a time, synchronously in the order they come, unless you explicitly tell them to be asynchronous by using a timeout or interval.

This means that your .append method will be executed and nothing else (disregarding any potential timeouts or intervals that may exist) will execute until that method have finished its job.

To summarize, there's no need for a callback since .append will be run synchronously.

Solution 2:

Although Marcus Ekwall is absolutely right about the synchronicity of append, I have also found that in odd situations sometimes the DOM isn't completely rendered by the browser when the next line of code runs.

In this scenario then shadowdiver solutions is along the correct lines - with using .ready - however it is a lot tidier to chain the call to your original append.

$('#root')
  .append(html)
  .ready(function () {
    // enter code here
  });

Solution 3:

Well I've got exactly the same problem with size recalculation and after hours of headache I have to disagree with .append() behaving strictly synchronous. Well at least in Google Chrome. See following code.

var input = $( '<input />' );
input.append( arbitraryElement );
input.css( 'padding-left' );

The padding-left property is correctly retrieved in Firefox but it is empty in Chrome. Like all other CSS properties I suppose. After some experiments I had to settle for wrapping the CSS 'getter' into setTimeout() with 10 ms delay which I know is UGLY as hell but the only one working in Chrome. If any of you had an idea how to solve this issue better way I'd be very grateful.

Solution 4:

I'm surprised at all the answers here...

Try this:

window.setTimeout(function() { /* your stuff */ }, 0);

Note the 0 timeout. It's not an arbitrary number... as I understand (though my understanding might be a bit shaky), there's two javascript event queues - one for macro events and one for micro events. The "larger" scoped queue holds tasks that update the UI (and DOM), while the micro queue performs quick-task type operations.

Also realize that setting a timeout doesn't guarantee that the code performs exactly at that specified value. What this does is essentially puts the function into the higher queue (the one that handles the UI/DOM), and does not run it before the specified time.

This means that setting a timeout of 0 puts it into the UI/DOM-portion of javascript's event queue, to be run at the next possible chance.

This means that the DOM gets updated with all previous queue items (such as inserted via $.append(...);, and when your code runs, the DOM is fully available.

(p.s. - I learned this from Secrects of the JavaScript Ninja - an excellent book: https://www.manning.com/books/secrets-of-the-javascript-ninja )

Solution 5:

I have another variant which may be useful for someone:

$('<img src="http://example.com/someresource.jpg">').load(function() {
    $('#login').submit();
}).appendTo("body");