Is there any way to determine the pixel length of a string in jQuery/JavaScript?
The length property returns the length of a string. The length property of an empty string is 0.
Wrap text in a span and use jquery width()
The contexts used for HTML Canvases have a built-in method for checking the size of a font. This method returns a TextMetrics
object, which has a width property that contains the width of the text.
function getWidthOfText(txt, fontname, fontsize){ if(getWidthOfText.c === undefined){ getWidthOfText.c=document.createElement('canvas'); getWidthOfText.ctx=getWidthOfText.c.getContext('2d'); } var fontspec = fontsize + ' ' + fontname; if(getWidthOfText.ctx.font !== fontspec) getWidthOfText.ctx.font = fontspec; return getWidthOfText.ctx.measureText(txt).width; }
Or, as some of the other users have suggested, you can wrap it in a span
element:
function getWidthOfText(txt, fontname, fontsize){ if(getWidthOfText.e === undefined){ getWidthOfText.e = document.createElement('span'); getWidthOfText.e.style.display = "none"; document.body.appendChild(getWidthOfText.e); } if(getWidthOfText.e.style.fontSize !== fontsize) getWidthOfText.e.style.fontSize = fontsize; if(getWidthOfText.e.style.fontFamily !== fontname) getWidthOfText.e.style.fontFamily = fontname; getWidthOfText.e.innerText = txt; return getWidthOfText.e.offsetWidth; }
EDIT 2020: added font name+size caching at Igor Okorokov's suggestion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With