jquery.excerpt.js

Trims a block-level element's text content to fit a set number of lines.

Usage

  1. Include jQuery 1.3+ and jquery.excerpt.js in your HTML
  2. Call $elem.excerpt(); to abbreviate $elem (a jQuery element) to 1 line. HTML tags are ignored: only text is excerpted.

Options (passed as the first parameter):

end
String or DOM node which should appear at the end of the excerpt, if we truncate.
always_end
String or DOM node which should appear at the end of the excerpt, regardless of whether we truncate. (If we truncate, end will appear before always_end.)
lines
Number of lines to display

excerpt() relies upon the web browser's actual rendering and layout. This means you can, for instance, generate lines which wrap around floated images. Be sure your img tags have hard-coded width and height, so that excerpt() uses the correct page layout before the browser actually finishes loading.

excerpt(), though heavily optimized, can be somewhat slow (because the browser itself needs to lay out the same text seven or eight times). Be aware of the potential impact on your page load time. (A complex page with five excerpts might suffer a 50-100ms delay on a typical browser.)

Examples

Constrained to 300px, this div will be reduced to a single line when the below button is clicked. All defaults will be used.

$div.excerpt()

Constrained to 300px, this div will be reduced to a three lines when the below button is clicked. There will be a button which restores the original text, too.

var o = $div.text(), $r = $('<a href="#" style="padding-left:5px">restore</a>'); $div.excerpt({ lines: 3, end: '[cut]', always_end: $r }); $div.find('a').click(function(e){e.preventDefault(); $div.text(o);});