Joined June 2013
·
Posted to
Calculate width of text from a DOM element or string.
over 1 year
ago
I had to do what @dakuan suggested, and it worked reasonably well. I also put the results of all my calculations in the dictionary, so I could take advantage of repetitive strings.
I've not yet tried it, but, if your browser support requirements are appropriate, I noticed the other day that canvas has some methods for getting the width of a piece of text that appear to give the same results as the DOM. I'd expect it to be much more performant, but I've not yet tried it.
@dakuan I'll leave a jQuery plugin, etc., as an exercise for the reader, but it does look like a canvas implementation can be much faster, about 50x in Firefox Aurora, about 7 in Chrome stable. Here's a jsperf test case: http://jsperf.com/measuring-text-width That is, I'm assuming I didn't mess anything up on my test case. :-D
Note that the canvas implementation returns a floating-point value. (Probably only an issue if you are mashing it to a string value or something…)