views:

171

answers:

5

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?

+6  A: 

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.

zombat
+1 Good trick. :-D
NawaMan
A: 

Sounds like something you'd have to hack. I don't believe the JavaScript runtime in any browser has an event you can hook into in between calculating the layout and displaying the element, so you can add it in a way that it can't be seen and doesn't affect the height (doesn't cause additional scrolling), and then show/hide it based on the width at this point. It's hacky and ugly, but because you don't have many event hooks it might be the only way to do it.

Rich
+1  A: 

Maybe you can append it invisible, then check it's width, and then consider to show or hide.

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

var div = $('#PlotPlace').children("div");

if(div.width() < 60)
    div.css({left:200})
Funky Dude
A: 

You can´t. At least not so easy. The text you insert is written in a specific font, which must be rendered by the browser, then you know the width of the element. By the Way, what exactly do you want to insert, with such a restriction? Wouldn´t it be simpler to cut the text within the output parameters?

MaikL80