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
I could not get any of the solutions listed to work 100%, so came up with this hybrid, based on ideas from @chmurson (which was in turn based on @Okamera) and also from @philfreo:
(function ($)
{
var calc;
$.fn.textWidth = function ()
{
// Only create the dummy element once
calc = calc || $('').css('font', this.css('font')).css({'font-size': this.css('font-size'), display: 'none', 'white-space': 'nowrap' }).appendTo('body');
var width = calc.html(this.html()).width();
// Empty out the content until next time - not needed, but cleaner
calc.empty();
return width;
};
})(jQuery);
this
inside a jQuery extension method is already a jQuery object, so no need for all the extra $(this)
that many examples have.white-space: nowrap
, just to ensure that it measures it as a single line (and not line wrap based on other page styling).font
alone and had to explicitly copy font-size
as well. Not sure why yet (still investigating).@philfreo
does.