CSS word ellipsis ('...') after one or two lines

user349072 picture user349072 · Jul 26, 2012 · Viewed 34.9k times · Source

I'm trying to create a word-wrap in JavaScript using CSS, and the condition is:

If DIV contains one very long word, such as "asdasfljashglajksgkjasghklajsghl", I want to display:

     |asdasfljashglajk...|

If DIV contains a long sentence, such as "if i had a dime for everytime i was told i can't", I want to display:

     |if i had a dime for|
     |everytime i was... |

I work with HTML, CSS, JavaScript. I can't use jQuery.

Please let me know if it's possible.

Answer

alecs.popa picture alecs.popa · May 7, 2013

I know I'm a bit late with the anwser but I just wrote a pice of code that accomplices that:

    if ($('your selector').height() > 50) {
        var words = $('your selector').html().split(/\s+/);
        words.push('...');

        do {
            words.splice(-2, 1);
            $('your selector').html( words.join(' ') );
        } while($('your selector').height() > 50);
    }

and of course you should save the jQuery selector in a variable so you don't query the DOM every time.