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 to create a table of widths for each character, but this is pretty unreasonable especially supporting Unicode and different type sizes (and all browsers for that matter).
I wrote a little tool for that. Perhaps it's useful to somebody. It works without jQuery.
https://github.com/schickling/calculate-size
Usage:
Fiddle: http://jsfiddle.net/PEvL8/
You can use the canvas so you don't have to deal so much with css properties:
jQuery:
I guess this is prety similar to Depak entry, but is based on the work of Louis Lazaris published at an article in impressivewebs page
The fit event is used to execute the function call inmediatly after the function is asociated to the control.
e.g.: $('input').autofit().trigger("fit");
Without jQuery:
Building off of Deepak Nadar's answer, I changed the functions parameter's to accept text and font styles. You do not need to reference an element. Also, the
fontOptions
have defaults, so you to not need to supply all of them.