October 7th 2008

Truncate Lengthy Text for Cleaner Display in ASP.NET ListView Using jQuery

Sometimes I need to display some lengthy text like a note in a ListView. If the text it too long though, I think it takes away from the page and makes things look pretty busy:

Live Demo | Download (HTML, CSS, JavaScript)


Before Image

The first way I solved this problem was by checking the length of the note. If it was longer than a set value, I would trim it and insert a LinkButton with its command value to set to Select. I would then show the full note in the SelectedItemTemplate of the ListView. There are at least two problems with this approach though:

A postback is needed to display the note. If you have a public facing site you would loose out on the text of the of note being indexed. Today, I was looking around and found another option http://henrik.nyh.se/2008/02/jquery-html-truncate which uses jQuery to truncate and hide any text greater than the length set and inserts more… or less links as appropriate. This solution takes care of the two problems noted above.


After Image


<script type="text/javascript">
    $(document).ready(function() {
        $('.note').truncate({ max_length: 50 });    

All the jQuery is doing here is selecting all of the items that have a class of “note” and calling truncate(). Be sure to checkout the demo.