0

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?

user3627265
  • 161
  • 1
  • 5
  • 18

1 Answers1

1

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.

Community
  • 1
  • 1
Superdrac
  • 1,208
  • 17
  • 29