Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim content of element and put "..." if the characters go over a certain limit?

I would like to trim a part of the <td> if it is too long. This will make sure the table doesn't get messed up. All the data in the following table is retrieved from a database. On the "Subject" part, how could I make the text shorten and put "..." if it goes over a certain character limit? Here is a screenshot of the table:

screenshot

As you can see if the subject gets too long it may mess up the table.

Is there any jQuery that will make the element trim only if it goes over a certain limit and put "..." at the end? I don't think a truncate plugin would work because it usually splits it up and makes a line break and I don't need it to show because all the person using this would have to do is click "View ticket" and they will see the full subject there.

I searched other questions on StackOverflow but I couldn't find one that is what I need.

like image 472
Nathan Avatar asked Sep 17 '11 06:09

Nathan


2 Answers

You might be able to use the CSS text-overflow: ellipsis property.

According to this compatibility table, it is supported by all major browsers.


Based on this answer, it looks like you also need to define table-layout: fixed on the table, and overflow: hidden and white-space: nowrap on the cells. The fixed table layout will also require you to adjust your column widths explicitly.

like image 117
Stuart Cook Avatar answered Nov 16 '22 00:11

Stuart Cook


Here is a little snippet that I used to see if an artists name was over 33 characters

// Elipses 
$('.artistName').each(function() {
    var that = $(this),
        title = that.text(),
        chars = title.length;

    if (chars > 33) {
        var newTitle = title.substring(0, 30) + "...";
        that.text(newTitle);
    }
});

Just replace the .artistName selector with the one for your table cell and update the character counts to reflect what you want.

like image 4
wesbos Avatar answered Nov 16 '22 00:11

wesbos