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
Element.getClientRects()
method returns a collection ofDOMRect
objects that indicate the bounding rectangles for each CSS border box in a client. The returned value is a collection ofDOMRect
objects, one for each CSS border box associated with the element. EachDOMRect
object contains read-onlyleft
,top
,right
andbottom
properties describing the border box, in pixels, with the top-left relative to the top-left of the viewport.
Element.getClientRects() by Mozilla Contributors is licensed under CC-BY-SA 2.5.
Summing up all returned rectangle widths yields the total text width in pixels.
document.getElementById('in').addEventListener('input', function (event) {
var span = document.getElementById('text-render')
span.innerText = event.target.value
var rects = span.getClientRects()
var widthSum = 0
for (var i = 0; i < rects.length; i++) {
widthSum += rects[i].right - rects[i].left
}
document.getElementById('width-sum').value = widthSum
})
Sum of all widths: px