How to call a function after jQuery .append
is completely done?
Here\'s an example:
$(\"#root\").append(child, function(){
// Action
Using MutationObserver can act like a callback for the jQuery append
method:
I've explained it in another question, and this time I will only give example for modern browsers:
// Somewhere in your app:
var observeDOM = (() => {
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
return function(obj, callback){
if( MutationObserver ){
// define a new observer
var obs = new MutationObserver(function(mutations, observer){
if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
callback(mutations);
});
// have the observer observe foo for changes in children
obs.observe( obj, { childList:true, subtree:true });
return obs;
}
}
})();
//////////////////
// Your code:
// setup the DOM observer (on the appended content's parent) before appending anything
observeDOM( document.body, ()=>{
// something was added/removed
}).disconnect(); // don't listen to any more changes
// append something
$('body').append('<p>foo</p>');
$.when($('#root').append(child)).then(anotherMethod());
In jquery you could use just after your append
$(function(){
//code that needs to be executed when DOM is ready, after manipulation
});
$() calls a function that either registers a DOM-ready callback (if a function is passed to it) or returns elements from the DOM (if a selector string or element is passed to it)
You can find more here
difference between $ and $() in jQuery
http://api.jquery.com/ready/
Cleanest way is to do it step by step. Use an each funciton to itterate through each element. As soon as that element is appended, pass it to a subsequent function to process that element.
function processAppended(el){
//process appended element
}
var remove = '<a href="#">remove</a>' ;
$('li').each(function(){
$(this).append(remove);
processAppended(this);
});
I have another variant which may be useful for someone:
$('<img src="http://example.com/someresource.jpg">').load(function() {
$('#login').submit();
}).appendTo("body");
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.