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 = $(\'.c
The textWidth
functions provided in the answers and that accept a string
as an argument will not account for leading and trailing white spaces (those are not rendered in the dummy container). Also, they will not work if the text contains any html markup (a sub-string
won't produce any output and
will return the length of one space).
This is only a problem for the textWidth
functions which accept a string
, because if a DOM element is given, and .html()
is called upon the element, then there is probably no need to fix this for such use case.
But if, for example, you are calculating the width of the text to dynamically modify the width of an text input
element as the user types (my current use case), you'll probably want to replace leading and trailing spaces with
and encode the string to html.
I used philfreo's solution so here is a version of it that fixes this (with comments on additions):
$.fn.textWidth = function(text, font) {
if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('').appendTo(document.body);
var htmlText = text || this.val() || this.text();
htmlText = $.fn.textWidth.fakeEl.text(htmlText).html(); //encode to Html
htmlText = htmlText.replace(/\s/g, " "); //replace trailing and leading spaces
$.fn.textWidth.fakeEl.html(htmlText).css('font', font || this.css('font'));
return $.fn.textWidth.fakeEl.width();
};