Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating text width

Tags:

jquery

I'm trying to calculate text width using jQuery. I'm not sure what, but I am definitely doing something wrong.

So, here is the code:

var c = $('.calltoaction');  var cTxt = c.text();  var cWidth =  cTxt.outerWidth();  c.css('width' , cWidth); 
like image 224
Dom Avatar asked Oct 17 '09 16:10

Dom


People also ask

How do I measure text size?

Point size measures from the height of the highest ascender (peak) to the baseline of the lowercase x. It then measures from the lowest descender (valley) of the font to the top of the lowercase x. Standardized fonts (e.g. Arial, Times New Roman, Calibri, etc.)

How do I get text size in HTML?

In HTML 5, you can just use the Canvas. measureText method (further explanation here). If you want to use the font-size of some specific element myEl , you can make use of the getCanvasFont utility function: const fontSize = getTextWidth(text, getCanvasFont(myEl)); // do something with fontSize here...

How do you find the pixel length of a string?

To determine the pixel length of a string in JavaScript and jQuery, we can put the string in a span and then use the jQuery width method to determine the width of the span. to get the span width document. querySelector . And then we set innerText to the string of the span.


1 Answers

This worked better for me:

$.fn.textWidth = function(){   var html_org = $(this).html();   var html_calc = '<span>' + html_org + '</span>';   $(this).html(html_calc);   var width = $(this).find('span:first').width();   $(this).html(html_org);   return width; }; 
like image 193
Rune Kaagaard Avatar answered Nov 15 '22 14:11

Rune Kaagaard