JQuery Plugin: Hide And Show “N” List Items

My previous post was on using JQuery to hide and show part of a list. The javascript was simple and clean, but it was also a little hacky, because it required a hard-coded height to collapse your lists to. I felt it would be a little more appropriate to go further in depth and actually take a parameter for the number of list items you want to show by default. Notice in my sidebar, I automatically hide list items in my categories and popular post lists. I used the first version with a hard-coded height, to handle those. Here’s a really simple plugin that takes an optional number of list items to show, on page load, collapses lists to that number, and appends a link to toggle the list display.

Here’s an example of how it looks after you’ve applied it to multiple lists. You can apply it to both ordered and unordered lists. You can apply a different collapse number to individual lists, or the same number to them all. You can also change the text of the toggle link. As you can see below, there are two completely different implementations, using default settings on the left, and custom settings on the right.

  • item number 1
  • item number 2
  • item number 3
  • item number 4
  • item number 5
  • item number 6
  • item number 7
  • item number 1
  • item number 2
  • item number 3
  • item number 4
  • item number 5
  • item number 6
  • item number 7

To implement the JQuery plugin, just bind the collapseList function to any ordered or unordered list. To stick with the default settings, use the first line of code in a document ready function. To customize the collapse number, and the toggle link text, use the second example.

$('ul.collapse').collapseList();
$('ul.collapse').collapseList({
	'collapseNum' : 4,
	'moreLinkText' : 'custom show text',
	'lessLinkText' : 'custom hide text'
});

Now to the goodies. Download the plugin! Here are links to both the unminimified and minified versions.

Download Full (1.39KB)Download Minified (790B)

This plugin has been tested in the following browsers:

Chrome Firefox Internet Explorer Safari Opera

I’m thinking a more robust version 2 could be in the works, but I don’t know what kind of customization would be needed. There are a lot of possibilities, and I’m just trying to decide what would help more. Feel free to put in requests so I can start working on putting something out.

3 Responses to “JQuery Plugin: Hide And Show “N” List Items”

  1. Fred says:

    How about change the collapseNum on the fly (like on window resize)…

  2. Mike says:

    Works great! I had to add some CSS to fix an overflow issue I encountered though:

    .collapseWrapper {
    overflow: hidden;
    }

    Perhaps this should be enforced by the plugin itself?