JCHASE11 JCHASE11 - 6 months ago 31
jQuery Question

How do I truncate a long unordered list with Jquery?

I am using wordpress to display a list of categories, sorted alphabetically. I want to use jQuery to append a "read more" link after the first 20 links. When the user clicks "read more" the rest of the categories slide down/appear. The HTML format of the list is below:

<ul id="catA">
<h2>Categories</h2>
<li class="cat-item">
<a title="title" href="#">Category Name</a>
</li>
<li class="cat-item">
<a title="title" href="#">Category Name</a>
</li>
<li class="cat-item">
<a title="title" href="#">Category Name</a>
</li>
...
</ul>


I want the
<a href="#">view all categories</a>
to be appended to the list after the 20rh category, and hiding everything after that. Before I attempt to write some code, any thoughts on the best way to go about this?

Answer

This is the simplest solution, but may work:

  • Let the 'view all' link created after the list, and give it an ID like '#catA-viewall';
  • Hide all items;
  • Show only the first 20;
  • On click on 'view all', we show all the elements.

    var $items = $('#catA').children();
    if ( $items.length > 20 ) {
        $items.hide().slice(0, 20).show();
        $('#catA-viewall').click(function () {
            $items.fadeIn(); // or .show()
            $(this).remove();
        });
    } else {
        $('#catA-viewall').remove();
    }