How can I make text-overflow: ellipsis
work in multi-line text without applying white-space: nowrap
, with pure javascript, without including any jQuery library and without specifying the number of lines?

- 882
- 1
- 15
- 28
-
See http://stackoverflow.com/questions/6572330/is-it-possible-to-use-text-overflowellipsis-on-multiline-text, http://stackoverflow.com/questions/6222616/with-css-use-for-overflowed-block-of-multi-lines, http://stackoverflow.com/questions/25448511/pure-css-ellipsis-for-three-or-more-lines-of-text, http://stackoverflow.com/questions/30499108/css-multi-line-ellipsis-cross-browser, http://stackoverflow.com/questions/14596777/how-to-trigger-text-overflow-ellipsis-on-multi-line-element, http://stackoverflow.com/questions/15909489/css-text-overflow-ellipsis-on-two-lines-is-it-possible, and others. – Sep 16 '15 at 19:45
1 Answers
I made alot of search for this and I couldn't find any simple and pure Javascript solution. So I ended up making my own :
function ellipsis(el){
var elheight = el.offsetHeight;
var eltxt = el.innerHTML;
while (elheight < el.scrollHeight){
eltxt = eltxt.substring(0, eltxt.length - 1);
el.innerHTML = eltxt + '...';
}
}
elheight
contains the actual height of the box (using offsetHeight
)
scrollHeight
gives us the height of the content of the box (including the overflowing text)
This function stores the content of the box inside eltxt
and then keep checking if the actual size of the box is still smaller than its content, and each time it removes 1 character from eltxt
and replace the content of the element by the new value of eltxt
plus the three points.
It works on Google chrome 4+, IE 8+, Firefox 3+, Safari 4+, and (I think) all Opera versions.
It's pretty simple and easy, but all I found on google is other long jQuery libraries with functions that you need to provide the number of lines you want in order for them to work etc..
EDIT
However, this solution is NOT the exact equivalent of text-overflow: ellipsis
as it doesn't hide the extra text, it removes it. So if your box has got some animations and its dimensions are supposed to change (get wider for example) then your text will not reappear as it was. In that case I recommend storing the text of the box outside of the function and then you run the function each time the dimensions of the box change by giving it the text of the box as 2nd parameter :
var myElementsText = myElement.innerHTML;
function ellipsis(el, txt){
var elheight = el.offsetHeight;
var eltxt = txt;
while (elheight < el.scrollHeight){
eltxt = eltxt.substring(0, eltxt.length - 1);
el.innerHTML = eltxt + '...';
}
}
function changeSize(el){
el.ClassName = 'new_class_with_different_dimensions';
function ellipsis(el, myElementsText);
}
Now if you run
changeSize(myElement);
The box will have its original text with the new ellipsis.

- 882
- 1
- 15
- 28