How to call a function after jQuery .append
is completely done?
Here\'s an example:
$(\"#root\").append(child, function(){
// Action
I think this is well answered but this is a bit more specific to handling the "subChild_with_SIZE" (if that's coming from the parent, but you can adapt it from where it may be)
$("#root").append(
$('<div />',{
'id': 'child'
})
)
.children()
.last()
.each(function() {
$(this).append(
$('<div />',{
'id': $(this).parent().width()
})
);
});
I know it's not the best solution, but the best practice:
$("#root").append(child);
setTimeout(function(){
// Action after append
},100);
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 )
I came across the same problem and have found a simple solution. Add after calling the append function a document ready.
$("#root").append(child);
$(document).ready(function () {
// Action after append is completly done
});
Yes you can add a callback function to any DOM insertion:
$myDiv.append( function(index_myDiv, HTML_myDiv){
//....
return child
})
Check on JQuery documentation: http://api.jquery.com/append/
And here's a practical, similar, example:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_prepend_func
$('#root').append(child).anotherMethod();