Skip to content

Instantly share code, notes, and snippets.

@wichert
Created July 31, 2015 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wichert/335f0ae09ed2cd002d61 to your computer and use it in GitHub Desktop.
Save wichert/335f0ae09ed2cd002d61 to your computer and use it in GitHub Desktop.
JavaScript function to dynamically crop text
// 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