views:

59

answers:

1

I have a <div> that I'm filling with a file name of indeterminable size. If the size exceeds the length of the <div> then I want it to be cut down and the last 3 characters replaced with a "...". Currently I have the following:

<div id="fileName" class="field-row" title="<%= fileName %>">
    <% if(fileName.Length > 20) { %>
        Filename: <%= fileName.Substring(0,20) %>...
    <% } else { %>
        Filename: <%= fileName %>
    <% } %>
</div>

This works fine but if I have a file name that is made up of i's vs. W's then the div will have unused space on the right.

For example:

"iiiiiiiiii.jpg"

is shorter than:

"WWWWWWWWWW.jpg"

...even though they have the same number of characters.

Is there a better way to do this that accounts for the length of the <div>?

Thank you,

Aaron

+2  A: 

Because of the differences in character width that you mentioned, it should be done client-side.

Here's a mostly-cross-browser, mostly-CSS way to do it: http://www.electrictoolbox.com/ellipsis-html-css/. It's not totally supported, but that's what the JavaScript fallback is for.* Basically, just use

#fileName {
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
}

Without any JavaScript, that gets you support for IE7-, Safari/Chrome, Opera, Konqueror.

http://www.quirksmode.org/css/textoverflow.html

If you feel that using JavaScript just to support Firefox is too hacky, you can stick with the pure CSS, and the overflowing text will simply be hidden. Try viewing the quirksmode page in FF and you'll see.


*Edit: after having tested the jQuery ellipsis plugin patch for FireFox, I can confirm it works quite nicely, and scales well enough, if you don't use the "live resize" (the only) option. With all of 26 elements and the live option, resizing took FireFox - on a beefy machine - down to its knees. Be careful with this option! It's a nice convenience, but the plugin does not look to be written terribly efficiently (and I don't have time to patch it right now).

Matt Ball
This ended up working like a charm and the code to download to cover FireFox is minimal as well. thank you.
Aaron Salazar
@Aaron: no problemo! Just for the record, though, your question **is** a duplicate of quite a few other SO questions.
Matt Ball