Created
March 6, 2009 21:53
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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); |
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});
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
very smart indeed!