Javascript: String width in pixels

     

One of the hardest things about doing web development - using the browser as your GUI - is that you have to get used to, and accept, “close enough” (actually, getting your clients used to that idea is probably harder). “Close enough” is in direct conflict with many things in computer science, so it’s a difficult pill to swallow.

Keeping that in mind…

I was chatting with one of my friends, and they asked if there was anyway to get the length of a string in pixels. He needed it mostly for form layouts - to align buttons with labels. The project I am working on I have a similar issue, but not related to buttons (more of a dynamic truncation “…” kind of thing).

There was no obvious way I could think of, so I set out to find a way to do it. This kind of works (see first paragraph). If you know a better way, please let me know…

The tricky part is font-families and text decorations and the like will change quite a bit from browser to browser OS to OS. So for this to work you’ll need to set a class on anything you want to be able to measure.

What this technique does, in a nutshell, is copy the text from the target area to an offscreen holding area. Then sets the class of the offscreen area to the class of the target area, and removes any padding or margins. After the class is set, it finds the X position of a span before and after the offscreen area and subtracts them.

The results are close - sometimes dead on. It works well for simple divs (which is what I need), and it works less well with buttons (mostly because you can’t set a style on a button in Safari).

Here are some example files - Public domain.

If you know of a better way to do this, I’d love to hear it.

Oh, and the program I am using to check the sizes is a nice free program called FreeRuler.