views:

822

answers:

3

Is there any way to determine the pixel length of a string in jQuery/JavaScript?

+6  A: 

wrap text in a div or span and use jquery width

Natrium
Don't forget: placement and styling of the div/span makes a difference, because wrapping can come into play.
Andy E
This does only return the width of the containing element but not the width of the text.
Gumbo
Using a `<span>` wrapper works the best, because a `<div>` is automatically set to 100% browser width.
fudgey
+2  A: 

I don't believe you can do just a string, but if you put the string inside of a <span> with the correct attributes (size, font-weight, etc); you should then be able to use jQuery to get the width of the span.

<span id='string_span' style='font-weight: bold; font-size: 12'>Here is my string</span>
<script>
  $('#string_span').width();
</script>
Topher Fangio
If you are worried about wrapping, ensure that your string contains non-breaking spaces: ` ` instead of a regular space.
Topher Fangio
A: 

Put it in an absolutely-positioned div then use clientWidth to get the displayed width of the tag. You can even set the visibility to "hidden" to hide the div:

<div id="text" style="position:absolute;visibility:hidden" >This is some text</div>
<input type="button" onclick="getWidth()" value="Go" />
<script type="text/javascript" >
    function getWidth() {
        var width = document.getElementById("text").clientWidth;
        alert(" Width :"+  width);
    }
</script>
Grinn