Search

1/14/2008

Text Truncation with JavaScript

Text Truncation with JavaScript

* Truncate the text to a length of your choosing
* Do not truncate in the middle of a word (only on a word boundary)
* Keep the page search-engine friendly by publishing the complete non-truncated text
* Add an ellipsis to the end of the truncated text
* Make the ellipsis a link that expands the text to full length. Once expanded it cannot be collapsed again (but that functionality could be added just as easily)
* Assumes that the content is plain text with no markup.


var len = 100;
var p = document.getElementById('truncateMe');
if (p) {
var trunc = p.innerHTML;
if (trunc.length> len) {
/* Truncate the content of the P, then go back to the end of the
previous word to ensure that we don't truncate in the middle of
a word */
trunc = trunc.substring(0, len);
trunc = trunc.replace(/\w+$/, '');
/* Add an ellipses to the end and make it a link that expands
the paragraph back to its original size */
trunc += '<a href="#" ' +
'onclick="this.parentNode.innerHTML=' +
'unescape(\''+escape(p.innerHTML)+'\');return false;">' +
'...<\/a>';
p.innerHTML = trunc;
}
}

沒有留言: