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.
-
possible duplicate of [Wait untill previous .append() is complete](http://stackoverflow.com/questions/1539841/wait-untill-previous-append-is-complete) – abc123 Dec 19 '13 at 20:42
-
1Perhaps the code responsible for the rendering could set some flag. – toniedzwiedz Dec 19 '13 at 20:42
-
This is not exactly kosher, but would adding a ` – salezica Dec 19 '13 at 20:47
-
Just use google chomre "inspect element" option to observe the HTML Code – Kirk Dec 19 '13 at 20:51
2 Answers
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
});

- 139,160
- 33
- 216
- 263
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:

- 631
- 1
- 10
- 25
-
If he's adding content from the result of an AJAX call, by definition he's already doing something in the success callback. – josh3736 Dec 19 '13 at 21:00
-
You're right, @josh3736, but he doesn't provide any code to know what specifically is being done. – psdpainter Dec 19 '13 at 21:16