Remus Remus - 4 months ago 15
jQuery Question

Check if span element contains more than 3 lines

I'm trying to do a trick with a span element. There is an image attached so that I can explain easier.

Left current behavior → Right desired one

enter image description here

So the idea is I need to display in the span element only 3 lines of text. Having more than 3 I need to make such that only 3 are displayed and the last word is [...] (when hover the remaining text is viewed - dis part is done).

I've tried something like this on the css side

span.itemMessage
{
display: block; /* or inline-block */
height: 37px;
overflow: hidden;
position: relative;
}


and yes it works ok, shows only 3 lines every time but if i have more I have no idea how can I handle the case that I was talking about.

I'm thinking of comparing the height of the text with the height of the span and if the height of the text is greater than do some .js, but I have no idea how to do this.

I have 40 messages that can be displayed and the name of the article which is between "" can be of any length.

var trimedMessage = message;

//try {
// var first = message.split('“');
// var second = first[1].split('”');
// var article = second[0];
// if (article.length >
// if (message.length > 80) {
// var newItem =
// }
//}
//catch (err) { }

return trimedMessage;


This is something that I've tried previously but due to the fact that the message is very dynamic I cannot handle all the cases.

So in the end my question is how can I calculate the difference between the span element height and the message. Or if any other ideas they are more than welcome

Thank you

PS: this is the HTML

<div class="notification ' + classColor + '">' +
'<a href="#">' +
'<i class="category-icon fa ' + classIcon + '"></i>' +
'<span class="abonnementMessage" data-toggle="tooltip" data-placement="left" title="' + abonnementMessage + '"maxlength="10">' + abonnementMessage + '</span>' +
'<small><i class="fa fa-warning">' + date + '</i> </small>' +
'</a>

Answer

There is a pure CSS solution to it. The trick is to use CSS line-clamp. Here is a working example: https://codepen.io/martinwolf/pen/qlFdp (it even contains a solution for browsers not supporting line-clamp)

Hope this helps!

Comments