user3627265
user3627265

Reputation: 191

Calculate the width of the string base on font size and font style

I'm trying to determine the width of the string based on the font size and font style.
But I'm not sure how to do it. I found a function on google, and I dont quite understand how it works.

$.fn.textWidth = function(text, font) {
    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
    $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
    return $.fn.textWidth.fakeEl.width();
};

I tested this out, and get an output, I can get the width of the string, but What if I declare the font style and size? I'm not sure how to do it. Any idea on this one?

Upvotes: 0

Views: 936

Answers (1)

Superdrac
Superdrac

Reputation: 1208

Use this one:

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

From this subject.

Upvotes: 1

Related Questions