public
Last active

A simple jQuery plugin to truncate a piece of text to a predefined amount of lines. It assumes pixel values of both the container and its line-height. Useful when you have multiple boxes with text in your design that require equal heights.

  • Download Gist
jquery.truncatelines.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
$.fn.truncateLines = function(options) {
options = $.extend($.fn.truncateLines.defaults, options);
 
return this.each(function(index, container) {
container = $(container);
var containerLineHeight = Math.ceil(parseFloat(container.css('line-height')));
var maxHeight = options.lines * containerLineHeight;
var truncated = false;
var truncatedText = $.trim(container.text());
var overflowRatio = container.height() / maxHeight;
if (overflowRatio > 2) {
truncatedText = truncatedText.substr(0, parseInt(truncatedText.length / (overflowRatio - 1), 10) + 1); // slice string based on how much text is overflowing
container.text(truncatedText);
truncated = true;
}
var oldTruncatedText; // verify that the text has been truncated, otherwise you'll get an endless loop
while (container.height() > maxHeight && oldTruncatedText != truncatedText) {
oldTruncatedText = truncatedText;
truncatedText = truncatedText.replace(/\s.[^\s]*\s?$/, ''); // remove last word
container.text(truncatedText);
truncated = true;
}
if (truncated) {
truncatedText = options.ellipsis ? truncatedText + ' ' + options.ellipsis : truncatedText;
container.text(truncatedText);
if (container.height() > maxHeight) {
truncatedText = truncatedText.replace(/\s.[^\s]*\s?...$/, ''); // remove last word and ellipsis
truncatedText = options.ellipsis ? truncatedText + ' ' + options.ellipsis : truncatedText;
container.text(truncatedText);
}
}
});
};
$.fn.truncateLines.defaults = {
lines: 8,
ellipsis: '...'
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.