Reputation: 160
Ok so I have a list and some of the text inside the list is to long so I want to use JavaScript and Jquery to trim the text and add ... to the end of the test if its longer than 30 characters.
<ul>
<li><a href="#">Long List item Long List item Long List item </a></li>
<li><a href="#">Smaller List item</a></li>
<li><a href="#">item</a></li>
</ul>
My Jquery at the moment:
$(function(){
$("ul li a").html(function(){
return $(this).html().substring(0,30);
});
$('.box ul li a').append(' ...');
});
This works but I want to add maybe an IF statment to only add the ... if the length of the text inside of the tag is more than 30 characters. How would I go about doing that?
Thanks
Upvotes: 1
Views: 51
Reputation: 781096
Test the length in the function that's creating the substring, and add the ellipsis there.
$(function(){
$("ul li a").html(function(i, html){
return html.length > 30 ? html.substr(0, 30) + " …" : html;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#">Long List item Long List item Long List item </a>
</li>
<li><a href="#">Smaller List item</a>
</li>
<li><a href="#">item</a>
</li>
</ul>
BTW, the current HTML of the element is passed as an argument to the callback function, so you don't need to use $(this).html()
inside it.
Upvotes: 5