Reputation: 79
I am dynamically adding blocks of HTML to a page with AJAX calls. I need to know the height of the element after its been added to the page, but I can't get an accurate result because the added element takes an unknown amount of time to render. Is there any way of insuring that some JS is run after an element is finished rendering on the page.
Upvotes: 2
Views: 275
Reputation: 145002
The DOM is manipulated synchronously, so the HTML is "fully rendered" at the moment when your call to appendChild
/append
/innerHTML
/etc returns.
What does not happen synchronously, though, is the loading of resources (ie images). So while you can check the rendered height of your newly inserted content on the line after you insert it, the height will not include the height of any images.
To work around this, you can explicitly specify the width and height of images – <img width=... height=...>
– or you could listen for the load
event on each of the newly inserted images. Each time the event fires, recalculate your element's height. (Note that this will happen once for each new image.) Something like:
$('#somediv').html('... <img src="..."> ...'); // or whatever
$('#somediv img').on('load', function() {
var h = $('#somediv').height();
// ...and do what you will with the height
});
Upvotes: 2
Reputation: 666
It's hard to know without seeing your markup and/or code, but if you're dealing with AJAX, you probably want to capture some logic in the .done()
method. Take a look here:
Also, you might want to take a look at jQuery's promises:
Upvotes: -1