Skip to content

Instantly share code, notes, and snippets.

@jjxtra
Last active March 7, 2024 18:30
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 jjxtra/46e083dca354f16955c7f225de7c41e6 to your computer and use it in GitHub Desktop.
Save jjxtra/46e083dca354f16955c7f225de7c41e6 to your computer and use it in GitHub Desktop.
Truncate multiline text in jquery without needing to pay for stupid licenses.
function truncateTextWithEllipsis(selector, text, maxHeight)
{
var el = $(selector);
el.text(text);
if (el.height() > maxHeight)
{
//console.log('Start shrink ' + text);
while (el.height() > maxHeight && text.length > 0)
{
//console.log(`Shrink ${el.height()}, ${maxHeight}, ${text.length}`);
text = text.substr(0, text.length - 1);
el.text(text + '…');
}
//console.log('Shrink el height: ' + el.height());
for (var i = text.length - 1; i > 0; i--)
{
var c = text[i];
console.log('Shrink punct ' + c);
if (c.toUpperCase() == c.toLowerCase())
{
//console.log('Shrunk at index ' + i);
text = text.substr(0, i);
break;
}
}
if (text.length > 0)
{
el.text(text + '…');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment