Calculating text width

Here’s a function that’s better than others posted because

  1. it’s shorter
  2. it works when passing an <input>, <span>, or "string".
  3. it’s faster for frequent uses because it reuses an existing DOM element.

Demo: http://jsfiddle.net/philfreo/MqM76/

// Calculate width of text from DOM element or string. By Phil Freo <http://philfreo.com>
$.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();
};

Leave a Comment

tech