Skip to content

Instantly share code, notes, and snippets.

@wireframe
Created March 6, 2009 21:53
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wireframe/75088 to your computer and use it in GitHub Desktop.
Save wireframe/75088 to your computer and use it in GitHub Desktop.
jquery plugin to truncate elements based on height instead of number of characters
/*
truncates elements that pass a certain height.
adds a "view more" link to display the rest of the content.
a different approach than standard truncation which relies on character counting.
character counting may not be desireable when elements have short words, but a
number of line breaks.
usage:
//using defaults
$('css_expression').summary();
//overriding options
$('css_expression').summary({maxHeight: 200, className: 'view-more'});
*/
(function($) {
$.fn.summary = function(options) {
return this.each(function() {
new $.Summary(this, options);
});
};
$.Summary = function(e, o) {
var element = $(e);
var options = o || {};
var maxHeight = options.maxHeight || 100;
var className = options.className || 'expand';
var textHeight = e.offsetHeight;
if (textHeight > maxHeight) {
element.css({overflow: 'hidden'});
element.height(maxHeight);
var moreLink = $("<a>View More</a>").click(expand).addClass(className);
element.after(moreLink);
}
function expand() {
element.animate({height: textHeight}, 'fast');
moreLink.hide();
};
};
})(jQuery);
@benomatis
Copy link

very smart indeed!

@benomatis
Copy link

A little trick here, would you want to actually nicely show a specific number of lines:

var lineHeight = parseInt($('css_expression').css('line-height'), 10);
finalHeight = lineHeight*3; // if you would like to show 3 lines
$('css_expression').summary({maxHeight: finalHeight});

@SY6Dave
Copy link

SY6Dave commented Apr 9, 2018

Very useful. Personally I added a couple of extra bits to include a View Less button -

In the $.Summary function:

var moreLink = $("<a>View More</a>").click(expand).addClass(className);
var lessLink = $("<a>View Less</a>").click(collapse).addClass(className);
element.after(moreLink);
element.after(lessLink);
lessLink.hide();

And then these amendments to the expand function:

function expand() {
  element.animate({height: textHeight}, 'fast');
  moreLink.hide();
  lessLink.show();
};

function collapse() {
  element.animate({height: maxHeight}, 'fast');
  lessLink.hide();
  moreLink.show();
};`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment