jQuery returns height of 0 for div element immediately after appending element

Go To StackoverFlow.com

4

I have a floating div that initially has no content. I use jQuery to append a set of elements to the div, and then immediately call the height method of the original div. The elements I am adding have a defined min-height in the stylesheet, while the floating div does not. The problem is that when I call height on the original div, I get 0.

If I use setTimeout to delay the call for even 1 millisecond, I get the proper height. My theory is that when I call the height method, the browser has not yet finished rendering the change to the DOM, so it hasn't yet set the hei?ht of the top level element. This height will vary, so using a fixed height is out. Does anyone know what might be causing this problem?

2012-04-05 18:06
by tabdulla
It's similar to this question, maybe an answer there will help - Fiona - myaccessible.website 2012-04-05 18:10
Thanks, Fiona. The problem is that I am dynamically adding this content after the window has loaded, and the event only fires once - tabdulla 2012-04-05 18:14
Is the element invisible? Just wondering - Alexander 2012-04-05 18:24
No, it's visible - tabdulla 2012-04-05 18:26
Are you using a method with a callback handler - MetalFrog 2012-04-05 18:27
No, there's no callback handler - tabdulla 2012-04-05 18:37


0

This should depend on the size of dom. If its large there will be slight delays.

2012-04-05 18:16
by StevenzNPaul
But is there any event that I can bind to, so that I only call methods on the updated div after the DOM has been fully updated?

I tried $(document).ready and $(window).load and it didn't help - tabdulla 2012-04-05 18:17

@tabdulla There is no event, however you can use a setTimeout with a very short delay, as you have found out. That's what I would go with - Kevin B 2012-04-05 18:23
Yeah, it just seems sort of hackish, but if that's the way, then I guess I can live with that - tabdulla 2012-04-05 18:26


0

If nothing works out then you may temporarily want to consider the deferred .then() function. Here s an example using jsFiddle: http://jsfiddle.net/yTTRq/

2012-04-05 18:27
by walmik
This fiddle is wrong, surely? The alert is called immediately. You need to wrap it in an anonymous function - mxcl 2013-02-18 19:34
Ads