Skip to content

Instantly share code, notes, and snippets.

@shaneparsons
Last active April 27, 2016 18:17
Show Gist options
  • Save shaneparsons/ed7a5042758fd7c042359a58f998723e to your computer and use it in GitHub Desktop.
Save shaneparsons/ed7a5042758fd7c042359a58f998723e to your computer and use it in GitHub Desktop.
jQuery - Calculate width of text from DOM element or string.
$.fn.textWidth = function (text, font, transform) {
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'))
.css('text-transform', transform || this.css('text-transform'));
return $.fn.textWidth.fakeEl.width();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment