I was looking for a way to add an ellipsis in text when it is more than a certain number of lines. I didn't want to use a plugin and I found a pure JS code from another answer. However, the ellipsis "..." is applied to every single element, even if it doesn't pass the limit of the numbers.
HTML:
<p class="product-title">This is my product title example</p>
CSS:
.product-title {
line-height: 1.4rem;
height: 2.8rem;
}
!! I added a height twice of the line-height to make text more than two lines to overflow. If I want three lines, I put three times the line-height.
JS:
function dotify(element) {
var limit = element.offsetTop + element.offsetHeight;
var dots = document.createElement('span');
if (element['data-inner'])
element.innerHTML = element['data-inner'];
else
element['data-inner'] = element.innerHTML;
dots.appendChild(document.createTextNode('...'));
element.style.overflow = 'hidden';
element.appendChild(dots);
while (dots.offsetTop + dots.offsetHeight > limit) {
dots.previousSibling.data = dots.previousSibling.data
.replace(/\W*\w+\W*$/, '')
}
}
jQuery(".product-title").each(function() {
dotify(this);
});
Edit with examples of before and after:
Before: Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.
After: Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua...