Pew Pew Laser Blog

Code. Glass art. Games. Baking. Cats. From Seattle, Washington and various sundry satellite locations.

jQuery - Hide Extra List Items (jQuery v1.3.1)

Last Update: 8.17.2010

Introduction

This version of the jQuery script worked with v 1.3.1 of the jQuery library, but not the more recent v1.4.2. Check out a script that works with jQuery v 1.4.2 here.

This is a handy way to tidy up long lists. This will hide extra items in a list, and add "show more" and "show fewer" links to show and hide the extra items in the list.


The Solution

For any unordered list with the specified class, this jQuery script will hide the fourth and higher elements in the list, and a link to show all of the list items. When that link is clicked, all list items are displayed, and that link is replaced by one that hidess the extra items again.


Code

function showAll(clickedLink) {
  $(clickedLink).toggle();
  $(clickedLink).next("a").show();
  $(clickedLink).parent().prev().children("li:gt(3)").show();
}

function showFewer(clickedLink) {
  $(clickedLink).toggle();
  $(clickedLink).prev("a").show();
  $(clickedLink).parent().prev().children("li:gt(3)").hide();
}

$(document).ready(function(){

  $("ul.collapse")
        .each( function() {
          $(this).children("li:gt(3)").hide();
          $(this).after('

Show AllShow Fewer

\n'); $("p.control a.show_fewer").hide(); }); $("p.control a.show_all").bind("click", function() { showAll(this); return false; }); $("p.control a.show_fewer").bind("click", function() { showFewer(this); return false; }); });

When the page is loaded, the jQuery script looks at each unordered list with the collapse class. The script hides all lis with an index higher than 3, adds both the "Show More" and "Show Fewer" links do the DOM, and hides the "Show Fewer" link. It then binds the showFewer() and showAll() functions to their links.

The showAll() and showFewer() functions toggle the visibility of their associated links, shows the appropriate other link, and then hides the extra list items.


Looking for more?

Back to Pew Pew Laser Articles

Contact Me