Skip to content

Instantly share code, notes, and snippets.

@markhepburn
Created September 9, 2010 00:08
Show Gist options
  • Save markhepburn/571107 to your computer and use it in GitHub Desktop.
Save markhepburn/571107 to your computer and use it in GitHub Desktop.
// From here, with a few improvements (options classes argument, ability to pass plain text in):
// http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript
(function($) {
$.textMetrics = function(el, classes) {
var h = 0, w = 0;
var div = document.createElement('div');
div = $(div);
document.body.appendChild(div);
div.css({
position: 'absolute',
left: -1000,
top: -1000,
display: 'none'
});
// 'el' might be html, or just plain text:
div.html($(el).html() || el);
// add any custom classes first:
div.addClass($.makeArray(classes).join(' '));
var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];
$(styles).each(function() {
var s = this.toString();
div.css({
s: $(el).css(s)
});
});
h = div.outerHeight();
w = div.outerWidth();
div.remove();
var ret = {
height: h,
width: w
};
return ret;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment