Created
July 31, 2015 12:22
-
-
Save wichert/335f0ae09ed2cd002d61 to your computer and use it in GitHub Desktop.
JavaScript function to dynamically crop text
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
// Look for all elements with a clip class, and remove words form them | |
// until the text fits in the available space. This requires the element | |
// to have a fixed (maximum) width and height. | |
function cropText(root) { | |
var victims = root.querySelectorAll(".clip"), | |
rest, html, victim, $victim, words, cropped; | |
for (var i=0; i<victims.length; ++i) { | |
$victim=$(victim=victims[i]); | |
// We can only measure when the item is visible, but make it transparent | |
// so we do not introduce flickering. | |
victim.style.opacity=0; | |
victim.style.display="block"; | |
words=$victim.text().split(/\s+/); | |
cropped=false; | |
rest=[]; | |
while (victim.scrollHeight>victim.clientHeight && words.length>1) { | |
rest.unshift(words.slice(-1)); | |
words=words.slice(0, -1); | |
html=words.join(" ") +" <a href='#' class='expand'>…»</a>"; | |
$victim.html(html); | |
cropped=true; | |
} | |
if (cropped) { | |
victim.className+=" cropped"; | |
$victim.html(html+" <span class='rest'>"+rest.join(" ")+"</span>"); | |
} | |
victim.style.opacity=null; | |
victim.style.display="inline"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment