Is there any way to determine the pixel length of a string in jQuery/JavaScript?
Don't forget: placement and styling of the div/span makes a difference, because wrapping can come into play.
Andy E
2010-01-13 15:24:40
This does only return the width of the containing element but not the width of the text.
Gumbo
2010-01-13 15:33:38
Using a `<span>` wrapper works the best, because a `<div>` is automatically set to 100% browser width.
fudgey
2010-01-13 15:42:45
+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
2010-01-13 15:19:55
If you are worried about wrapping, ensure that your string contains non-breaking spaces: ` ` instead of a regular space.
Topher Fangio
2010-01-13 16:21:51
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
2010-01-13 15:26:26