whamsicore
whamsicore

Reputation: 8700

Javascript: unable to get height of newly created element

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?

Upvotes: 3

Views: 918

Answers (2)

Galled
Galled

Reputation: 4206

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.

Upvotes: 0

Brett Walker
Brett Walker

Reputation: 3576

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.

Upvotes: 1

Related Questions