I know this answer is very old, but I thought I'd share a similar problem and solution since it's very relevant.
I have a responsive site that has some paragraphs that need to cut off after 3 lines and add a link that essentially exposes the remaining text when clicked, for aesthetic reasons.
So it's crucial that I keep all of the text handy rather than refresh the page every time the screen size changes (that's the purpose of responsive).
Anyway, here's my elegant solution:
/**
* @name - Ellipsify
* @desc - trims and adds ellipsis to element when element text height is greater than element height
* @param - [required] (string)identity - string containing jquery selector used to create object group (array) based on selector
* @function : _init - calculates each element and determines need for ellipsis, then truncates text as needed
*/
var Ellipsify = function(identity) {
if (identity) {
this.identity = identity;
this.group = $(this.identity);
if (this.group.length > 0) {
this._init();
}
}
};
Ellipsify.prototype = {
_init : function() {
var that = this;
that.group.each(function() {
if ($(this).children('.hidden').length > 0) {
$(this).children(':not(.hidden)').text($(this).children(':not(.hidden)').text().replace('...',' ') + $(this).children('.hidden').text());
$(this).children('.hidden').remove();
}
if ($(this).children().outerHeight() > $(this).innerHeight()) {
$(this).append('<span class="hidden"></span>');
while ($(this).children(':not(.hidden)').outerHeight() > $(this).innerHeight()) {
var paragraph = $(this).children(':not(.hidden)').text().replace('...', '');
var lastword = paragraph.substring(paragraph.lastIndexOf(' '));
$(this).children(':not(.hidden)').text(paragraph.substring(0, paragraph.lastIndexOf(' ')) + '...');
$(this).children('.hidden').text(lastword + $(this).children('.hidden').text());
}
}
});
},
};
The HTML looks like this:
<p><span>Big paragraph of text goes here.</span></p>
and the CSS is simply:
p {
font-size:1em;
line-height:1.5em;
height:4.5em;
width:100%;
overflow:hidden;
}
.hidden {
display:none;
}