Skip to content

Instantly share code, notes, and snippets.

@dougkeeling
Created December 4, 2020 18:20
Show Gist options
  • Save dougkeeling/7285ad82aac4607ce79687d42d9d5eda to your computer and use it in GitHub Desktop.
Save dougkeeling/7285ad82aac4607ce79687d42d9d5eda to your computer and use it in GitHub Desktop.
[Truncate overflowing text boxes] Combination of JS, CSS, and HTML to modify responsive textboxes that need to be limited to a specific height, based on font-size and line-height #javascript #jquery #css #html
jQuery(function($){
function truncateToEllipsis(textboxes) {
function doTruncate(containers) {
for (var i = 0; i < containers.length; i++) {
var cntnr = $(containers[i]);
// The original content for this textbox should be place in an attribute
// called "data-text". The script will modify the original content, so we
// need to grab the original every time we need to recalculate based on
// window resize.
var pureText = cntnr.attr('data-text');
// Reset the HTML content to its original state.
cntnr.html(pureText);
// Begin processing the content
cntnr.html('<span>' + cntnr.html().replace(/ /g,'</span> <span>') + '</span>');
var words = Array.prototype.slice.call(cntnr.find("span"), 0).reverse();
var lastw = null;
for (var j = 0; j < words.length; j++) {
var w = $(words[j]);
var wbot = w.height() + w.offset().top;
var wleft = w.offset().left;
var wright = wleft + w.width();
if (wbot <= (cntnr.offset().top + cntnr.height()) && wleft >= (cntnr.offset().left) && wright <= (cntnr.offset().left + cntnr.width())) {
lastw = words.length - j - 1;
break;
}
}
cntnr.html(lastw === null || lastw === (words.length - 1) ? cntnr.text() : (cntnr.text().split(' ').slice(0, lastw).join(' ') + '...'));
}
}
if (textboxes instanceof Array) {
// If there are multiple textboxes that need to be checked
for (var i = 0; i < textboxes.length; i++) {
doTruncate($(textboxes[i]));
}
} else {
// If only one textbox needs checked
doTruncate($(textboxes));
}
}
// Call the function the first time
truncateToEllipsis($('.check-overflow'));
// Then run it again on window resize
$(window).on('resize', function(){
// Separate function that keeps resize from calling this
// function in rapid succession. See separate gist for
// this function.
waitForFinalEvent(function(){
truncateToEllipsis($('.check-overflow'));
}, 500, "check for overflown text"); // Requires a unique string, can be anything.
});
});
$lh: 25px; // Needs to be a set value with units
$lines: 3;
.textbox {
width: 100%;
font-size: 14px; // Needs to be a set value with units
line-height: $lh;
max-height: calc(#{$lh} * #{$lines});
overflow: hidden;
position: relative;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment