Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut the string in javascript so that it fits exactly two lines & add ... at the end

I have a requirement where in i have to display the text for two lines & add ... if its overflowing My div Width is fixed.(Even height can be considered as fixed).

Actual text looks like this:

1

Lorem Ipsum is simply
dummy text of the printing
and typesetting industry.

2

Lorem Ipsum is simply text
of the printing and types
industry.

Expected:

1

Lorem Ipsum is simply
dummy text of the print...

2

Lorem Ipsum is simply text
of the printing and typ...

I do not want to overload with plugins(three dots jquery plugin does that).

I'm planning to do just by cutting(split) the string as div width is fixed.

Thanks in Advance.

like image 217
jaan Avatar asked Jul 29 '10 00:07

jaan


2 Answers

UPDATE: Looks like text-overflow is only useful for horizontal truncation.

Here's a little jQuery that should work.

Try it out: http://jsfiddle.net/UfxYQ/

var $container = $('#container');
var $text = $('#text');
var originalText = $text.text();
var temp = originalText;

if( $container.outerHeight() < $text.outerHeight() ) {

    while($container.outerHeight() < $text.outerHeight()) {
        $text.text( temp = temp.substr(0, temp.length-1) );
    }
    $text.text( temp = temp.substr(0, temp.length-3) );
    $text.append('...');
}

HTML

<div id='container'>
    <span id='text'>Lorem Ipsum is simply
        dummy text of the printing
        and typesetting industry.
    </span>
</div>​

CSS

#container {
    width: 150px;
    height: 50px;
    line-height: 25px;
    position: relative;
}

You won't have full cross browser support, but close. There's a CSS property called text-overflow that is supported in IE6+, Safari, Konqueror, and Opera (with an Opera specific property).

#myOverflowDiv {
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
}

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

http://www.quirksmode.org/css/contents.html#t413

like image 66
user113716 Avatar answered Sep 17 '22 07:09

user113716


The CSS text-overflow property is the nicest way, but it's not supported by all browsers yet. If you want to use Javascript, you could create an offscreen element. Use CSS (generated by the script) to give it the same width and font as your target, with a height of '2em' (i.e. 2 lines). Run a loop, adding the text into it one letter at a time, until either you run out of letters or the height changes. When the height increases you know you've exceeded two lines.

Of course you need to account for the width of the "..." as well, so you might append it to the letter you're about to add.

Be sure the element is offscreen rather than using "display: none", as non-displayed elements have no height. "visibility: hidden" might work; I haven't tried.

like image 23
Rena Avatar answered Sep 21 '22 07:09

Rena