Skip to content

Instantly share code, notes, and snippets.

@joshbeckman
Created September 25, 2013 21:55
Show Gist options
  • Save joshbeckman/6706624 to your computer and use it in GitHub Desktop.
Save joshbeckman/6706624 to your computer and use it in GitHub Desktop.
Truncate strings of text and append a link to show the full text
var len = 100;
var p = document.getElementsByClassName('truncate');
if (p) {
for(i=0;i<p.length;i++){
var trunc = p[i].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[i].innerHTML)+'\');return false;">' +
'...<\/a>';
p[i].innerHTML = trunc;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment