views:

310

answers:

2

I have a div which contains text. The text should be shortened to two lines and "..." added at the end to point that there's more.
Since the font and font size may vary according to different users' settings (for example: browser "text size" settings, different browsers, etc.), I need to do this dynamically on the client side.

What is the best strategy to do this?
Thanks.

A: 

You need to define the number of characters in the text you want visible. Then walk through the text with a for loop, until you reach your defined number of characters while saving the characters you've been through into a string variable. Once you reach the defined number of characters, the for loop ends and you append the string "..." to the build string variable. That's your new text for the container. Here's some code:

nchars = 50;
div = document.getElementById("your_div_with_text");
divText = div.innerHTML;
newDivText = "";
for(var i = 0; i < nchars; i++){
   newDivText += divText[i];
}
newDivText += "...";
div.innerHTML = newDivText;

As for the issue with the fonts and font size, you could probably just set a CSS class containing font size and font family, that looked the best in all browsers.

brozo
From a purely typographical based point of view the string "..." is not equivalent to the ellipsis character (… or …) please consider using one of these instead of "..." ;)
Frozenskys
Don't do this with the `innerHTML` property. You could end up stripping closing tags from the resulting HTML, which could cause serious problems.
Andy E
Thanks, but it's not what I'm looking for. I can't specify the number of characters, it has to be dynamic.
Nir
+2  A: 

There are a few CSS features that Microsoft pioneered and has had available to developers in Internet Explorer for a long time now. One of those features is the text-overflow property, which is now in CSS3 and has implementations in Safari, and Opera. However, firefox still does not support this feature.

For a cross browser JavaScript implementation of the ellipsis feature for the jQuery framework, you may be interested in checking out the following article:


UPDATE:

Since jQuery is not an option, you may want to check the following:

Daniel Vassallo
Thanks, but I can't use it if it's not cross-browser, and we don't use jQuery.
Nir
Thanks for the links, mate.
Nir