Created
September 25, 2013 21:55
-
-
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
This file contains 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
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