How to call a function after jQuery .append
is completely done?
Here\'s an example:
$(\"#root\").append(child, function(){
// Action
the Jquery append function returns a jQuery object so you can just tag a method on the end
$("#root").append(child).anotherJqueryMethod();
I encountered this issue while coding HTML5 for mobile devices. Some browser/device combinations caused errors because .append() method did not reflect the changes in the DOM immediatly (causing the JS to fail).
By quick-and-dirty solution for this situation was:
var appint = setInterval(function(){
if ( $('#foobar').length > 0 ) {
//now you can be sure append is ready
//$('#foobar').remove(); if elem is just for checking
//clearInterval(appint)
}
}, 100);
$(body).append('<div>...</div><div id="foobar"></div>');
I ran into a similar problem recently. The solution for me was to re-create the colletion. Let me try to demonstrate:
var $element = $(selector);
$element.append(content);
// This Doesn't work, because $element still contains old structure:
$element.fooBar();
// This should work: the collection is re-created with the new content:
$(selector).fooBar();
Hope this helps!
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
});
For images and other sources you can use that:
$(el).one('load', function(){
// completed
}).each(function() {
if (this.complete)
$(this).load();
});
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.