Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine Pixel Length of String in Javascript/jQuery?

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

like image 783
GSto Avatar asked Jan 13 '10 15:01

GSto


People also ask

How do you find the length of a string in JavaScript?

The length property returns the length of a string. The length property of an empty string is 0.


2 Answers

Wrap text in a span and use jquery width()

like image 198
Natrium Avatar answered Sep 22 '22 17:09

Natrium


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.

like image 39
Lux Avatar answered Sep 21 '22 17:09

Lux