3

After updating the DOM with a new element (e.i. body.append(html)), I cannot immediately get the height of the newly updated element (e.g. body.height()). A partial fix is setting a time interval and getting the height at the end of time interval (setTimeout("alert(body.height)", 500)).

Any better ideas? Like a callback after DOM completely updates? Thanks.

Edit: This only happens when there is a lot going on in the background (i.e. when page first loads). It would seem like the page update is almost instantaneous if nothing else is being processed. What I need is a callback, or an indicator of when the DOM is reformed!

Edit: The problem is from the browser being 'distracted' by other processes, which makes the browser unable to update immediately after the append of the element. How do I fix this?

whamsicore
  • 8,320
  • 9
  • 40
  • 50
  • 1
    By any chance are you appending the HTML in an asynchronous call, like an ajax query? – JohnFx Nov 22 '11 at 02:22
  • It's difficult to recreate the problem right now as it is caused by the entire page loading (I am still using lamp) – whamsicore Nov 22 '11 at 05:25

2 Answers2

1

The timeout method works because the rendering engine is given a chance to display the new element there by giving it a change to render it and thus assigning it a height.

You can set the timeout to 0 and still have the same effect.

Brett Walker
  • 3,566
  • 1
  • 18
  • 36
0

With jQuery works fine for me.

In the jsfiddle demo I put the next code:

$(function(){
    var jTest = $('#test');

    console.log('The height:',jTest.innerHeight(),jTest.height()); //Show me 'The height: 20 20'

    jTest.append('<div><br/>How are you?</div>');
    console.log('The height:',jTest.innerHeight(),jTest.height()); //Show me 'The height: 60 60'

});

Unless you mean javascript only solution or put a jsFiddle demo to show your error.

Galled
  • 4,146
  • 2
  • 28
  • 41
  • It works because there is nothing else being processed so the browser updates almost immediately. However, if the browser is slowed down by other processes, this will not work – whamsicore Nov 22 '11 at 02:47
  • What kind of process? If is ajax I recomend to you call a function at the end of the request (using `$.ajax()`), otherwise you could do a `setTimeOut` to see if the process has been ended and then call your function to see the height. – Galled Nov 22 '11 at 02:49