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:
Lorem Ipsum is simply
dummy text of the printing
and typesetting industry.
Lorem Ipsum is simply text
of the printing and types
industry.
Expected:
Lorem Ipsum is simply
dummy text of the print...
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With