I\'d like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?
If it\'s not built-in, my only idea is t
Here's one I whipped together without example. It looks like we are all on the same page.
String.prototype.width = function(font) {
var f = font || '12px arial',
o = $('')
.text(this)
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
Using it is simple: "a string".width()
**Added white-space: nowrap
so strings with width larger than the window width can be calculated.