JavaScript: check the width of the <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 this line only if the width of the resulting text is less than 60 pixels. How to check the width before placing an object?
Unfortunately, a div will only have a width value after rendering it in the DOM.
I would add this content to an inconspicuous area of โโthe document, maybe even absolutely positioned so that there was no disruption to the flow, and make sure that it is set to "visible: hidden". Thus, it will be inserted into the DOM and will be displayed, but will be invisible to the viewer.
Then you can check the width on it and move it to the desired position and set โvisibility: visibleโ in this place. Otherwise, you can remove it from the document.
Perhaps you can add it invisible, then check its width, and then consider to show or hide.
$("#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}) It seems like you have to hack. I donโt believe that JavaScript runtime in any browser has an event that you can connect between calculating the layout and displaying the element, so you can add it in such a way that it cannot be seen and does not affect the height (does not cause additional scrolling), and then show / hide it depending on the width at that point. It is hacked and ugly, but due to the fact that you do not have many event hooks, this may be the only way to do this.
You can not. At least not so simple. The text you paste is written in a specific font that should be displayed by the browser, then you know the width of the element. By the way, what exactly do you want to insert with this restriction? Wouldn't it be easier to cut the text in the output parameters?