Andrew Sellenrick
Andrew Sellenrick

Reputation: 1016

Element.height() incorrect because browser hasn't finished rendering it?

I am appending div1 into div2 and then getting the height() of div2. If I wait 50ms before calling height() I get a different height. It seems like I am getting the height before the browser finishes rendering div1. Anyone have an idea as to how I can fix this. I am adding quite a few elements and need to check the height after every one, so having a delay between each seems like it could add up to quite the delay.

$(div2).append(div1);
console.log(div2.height()) // 295

where as...

$(div2).append(div1);
window.setTimeout(function(){
    console.log(div2.height()) // 245
},50)

Upvotes: 2

Views: 497

Answers (2)

mm-user
mm-user

Reputation: 36

put your code inside

$( document ).ready(function() {
 // your code
});

it will work

Upvotes: 0

jfriend00
jfriend00

Reputation: 707318

There are certain properties you can request that will force a layout. For example, if you request any of these properties:

  • offsetTop
  • offsetLeft
  • offsetWidth
  • offsetHeight
  • scrollTop/Left/Width/Height
  • clientTop/Left/Width/Height

the browser will layout that element before returning the value. If you have a complicated layout, you may need to request properties on more than one object to get proper layout of several items.

See this answer and this article for more details and working demos of the concept.

Upvotes: 1

Related Questions