Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Check width of a <div> object before placing it

Consider:

$("#PlotPlace").append('<div style="position:absolute;left:200px;top:40px;font-size:smaller">Hello world!</div>');

I need to execute that line only if the width of the resultant text would be less than 60px. How can I check the width before placing the object?

like image 938
KalEl Avatar asked Nov 16 '09 20:11

KalEl


1 Answers

Unfortunately, the div will only have a width value once it is rendered into the DOM.

I would append that content to an inconspicuous area of the document, perhaps even absolutely positioned so that no flow disruption occurs, and make sure that it is set to "visibility:hidden". That way it will be inserted into the DOM and be rendered, but be invisible to the viewer.

You can then check the width on it, and move it into position and set it to "visibility:visible" at that point. Otherwise, you can remove it from the document.

like image 137
zombat Avatar answered Sep 29 '22 19:09

zombat