I'm creating DOM elements dynamically (more specifically, using jQuery to create a DIV containing some text with css "width:auto", and using a "font-face" font, in the page OnLoad event) but find that the width of the div is not the expected size (specifically, the width is wrong) inmediatamente after I create it and add it to the DOM tree. I need to know the width/height of the element because I will be doing some dynamic layout on it.
As a workaround, I use the following code after creating the elements:
By delaying the completion of my layout with this extra timeout, everything works perfectly, with all element sizes exactly as expected (In the latest Chrome on Ubuntu Linux)
However, this klugey timer delay offends my sensibilities and is clearly unsafe... Is there any way to force accurate dimension calculations with a specific command? Or, is there an event I can register that will fire only once all the DOM elements have been correctly sized, after new dynamic elements are created? (I am picturing something like the IMG onload event, which allows you to figure out the proper dimensions of an image once it has been loaded)
tl; dr: Is there a guarantee as to when the width of a newly-created DOM object will be accurate?
Gracias por su ayuda!
preguntado el 08 de enero de 11 a las 20:01
How are you trying to get the width? .css("width"), or .width(),
You should be using .width(), as .css("width') wont return anything except auto (if no width was specified in some style)
It should give width even after immediate appending.
You could get the width by getting the width of the element you add the new div to. Since the width of the new div is set to auto they should be the same.
This will however not work for the height.