I need to pause execution of javascript until after the DOM changes are completed. I am making DOM changes with jquery append and setting some post variables with attributes of the appended image. I’ve looked at similar questions about this but none seem to be relevant to what I am wanting to do. Here is the code:
var newImage = new Image();
newImage.src = *src is retrieved from previous variable*;
newImage.style.display = "none";
$('body').append(newImage);
var postData = {
height: $('img:last')[0].height,
width: $('img:last')[0].width
};
In some cases the append will finish and I will get the correct values for height and width, but most of the time the DOM hasn’t finished and I just get 0’s for the height and width. How can I make the javascript wait for the DOM to finish its changes? I’ve tried messing around with jQuery .ready but I can’t seem to get it right.
You need to put an
onloadhandler on thenewImageobject, and then initiate the rest of your code from that handler, e.g.: