Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate Text in ul li anchor tag

Here is my html ,

<ul class="test">
    <li><a href="#">python</a></li>
    <li><a href="#">Truncate should apply here </a></li>
    <li><a href="#">c</a></li>
    <li><a href="#">cpp</a></li>
    <li><a href="#">java</a></li>
    <li><a href="#">.net</a></li>
    <li><a href="#">This is really a long text in this ul </a></li>
    <li><a href="#">This is another really a long text in this ul </a></li>
</ul>

I want to truncate the text in anchor tag , if the length of text is higher than 6 chars.

The output should like ,

    python
    Trun..
    c
    cpp
    java
    .net
    This..
    This..

How can i do this using Jquery ?

like image 540
Nishant Nawarkhede Avatar asked Dec 12 '25 23:12

Nishant Nawarkhede


2 Answers

You can do something like this:

$('ul.test li a').each(function() {
    var text = $(this).text();
    if(text.length > 6) {
        $(this).text(text.substring(0, 4) + '..')
    }
});

Fiddle Demo


If you want to use pure CSS then you can use text-overflow: ellipsis property:

ul.test li a {
    width: 45px;
    display: block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

However, you cannot control the number of limited characters before putting ellipsis using this approach.

Fiddle Demo

like image 158
Felix Avatar answered Dec 15 '25 22:12

Felix


Try below CSS

a {
    width: 50px;
    display: block;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

http://jsfiddle.net/W6EWF/

like image 26
Sridhar Narasimhan Avatar answered Dec 15 '25 23:12

Sridhar Narasimhan