How can you measure the space that text will take in Javascript?

In Javascript, I have a specific line, and I would like to somehow measure how much space (in pixels) it will take within a specific element.

Basically, I have an element that will pop up above everything else (e.g. a tooltip), and I need to set its width manually through Javascript so that it adjusts the text inside. I can’t make it “automatically grow”, naturally, as an inline element will grow horizontally to support its children.

Windows has APIs that do this. Is there a way to do the same in Javascript?
If there is no decent way, what approach do you think is possible? (For example, try a different width and check the height to make sure that it did not pass a certain threshold).

The smaller the "pixel values", the better, I can make hardcode in my JS.

+6
javascript css text layout
source share
3 answers

Given this HTML <span>text here</span> , you need to read the offsetWidth attribute of the range, which is only assigned when the element itself is added to the DOM without a style that makes it invisible. Technically, this means that the browser must be able to visually load the element into the DOM in order to be able to create and assign the offsetWidth attribute.

Something like this will work:

 var span = document.createElement("span"); span.appendChild(document.createTextNode("text here")); span.style = ""; // to make sure the elment doesn't have "display: none" or such document.body.appendChild(span); // adding it to the DOM var textWidth = span.offsetWidth; // be sure to hide or remove the span if you don't need it anymore 
+3
source share

This is easy to use in JavaScript. I am using Prototype in this example.

 <span id='text' style='border:1px solid #000000;font-size:14px'>hello this is sample text</span> <script type="text/javascript"> alert($('text').getWidth()) </script> 
+1
source share

All Articles