Is there any way to determine the pixel length of a string in jQuery/JavaScript?
Is there any way to determine the pixel length of a string in jQuery/JavaScript?
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>
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>
Maybe it will useful for some
const getMaxPixelsOfStrings = ({ strings, styles = {} }) => {
const spans = strings.map(str => {
const span = document.createElement('span')
span.append(str)
Object.assign(span.style, {
position: 'absolute',
...styles,
})
return span
})
document.querySelector('html').prepend(...spans)
const maxPixels = Math.max(...spans.map(span => span.getBoundingClientRect().width))
spans.forEach(span => span.remove())
return maxPixels
}
usage
getMaxPixelsOfStrings({
strings: ['One', 'Two', 'Three', 'Four', 'Five'],
styles: {
fontSize: '18px',
letterSpacing: '1px',
},
})