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);
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.)
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...
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.
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; };
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