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
The better of is to detect whether text will fits right before you display the element. So you can use this function which doesn't requires the element to be on screen.
function textWidth(text, fontProp) {
var tag = document.createElement("div");
tag.style.position = "absolute";
tag.style.left = "-999em";
tag.style.whiteSpace = "nowrap";
tag.style.font = fontProp;
tag.innerHTML = text;
document.body.appendChild(tag);
var result = tag.clientWidth;
document.body.removeChild(tag);
return result;
}
Usage:
if ( textWidth("Text", "bold 13px Verdana") > elementWidth) {
...
}