Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Accurate Dimensions for a newly-created DOM object

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) immediately 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:

SetTimeout(complete_layout,100)

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?

Thanks for your help!

like image 533
drcode Avatar asked Jan 08 '11 20:01

drcode


1 Answers

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)

$("#foo").width();

It should give width even after immediate appending.

like image 185
Patrick Evans Avatar answered Oct 31 '22 12:10

Patrick Evans