tags:

views:

152

answers:

4

I'd love to know how long a string is when it appears on the screen. We're not using a fixed width font, so:

"Our mother's tummy makes dummy noises."

is much wider than:

"Lilly Leadbetter lives life leisurely."

Is there a way to tell how long something is by the characters? I don't need pixel perfect accuracy, just long enough to ellipse at roughly the right spot. CSS overflow won't help, because I can't attach the ellipse after CSS has determined how long it is.

+7  A: 

Here's a related question with at least a partial solution. Basically the technique is to render the text in a hidden <span> and then (using JavaScript) measure the pixel width of the span, then chop off characters until it fits in your target width.

And here's a jQuery plugin that encapsulates this sort of functionality, linked from this related question.

Jordan
+2  A: 

Unless you're using a fixed width font, I don't think there's any simple way to tell. Perhaps the easiest way is to render the candidate text and see how long it is.

Server-side, this is a bit hit-and-miss because you don't know for sure what the browser is going to do with the text. You could use GD (or something like that) and your best guess what font and size the browser will use but is it worth the trouble when you can't trust your guesses?

Client side in javascript (or whatever) you can have the browser render the text and look to see how long the rendered DOM object is (as Jordan said).

One solution, though perhaps very hard psychologically, is to understand that web page rendering is not typography. You do not have control. You do your best, accept the limitations and move on to the next problem. Technically simple but maybe hard to accept.

fsb
A: 

You can use the truncate helper function. Even if you know about the visual length, you cannot probably optimize it for all browsers/browser window resizes.

Sohan
+2  A: 

Ordinarily I'd agree with fsb that you have to understand that on the web you don't have pixel-perfect control over everything. It's not print. Choose a reasonable length and chop it off server-side, you can avoid chopping in the middle of a word to make it look a little better.

If you insist on a perfect length though, check out ThreeDots, a jQuery plugin.

Adam Stegman
interesting plugin … i wonder how it would perform on a page with a few hundred string to truncate … in IE6 … for example …
fsb
Wow, ThreeDots is amazing... i'm definitely going to check it out!
aronchick