jQuery collapsible menu

Implementing a collapsible menu with jQuery requires some basic knowledge of how events and triggers work. We start with a basic menu like this:

<ul id="menu">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3
        <li>Sub-item 1</li>
        <li>Sub-item 2</li>
<li>Item 4</li>
<li>Item 5
        <li>Sub-item 3</li>
        <li>Sub-item 4</li>
        <li>Sub-item 5</li>
<li>Item 6</li>

We want each item that contains a sub-menu have a plus sign that indicates the presence of a sub-menu. Additionally, when an item is clicked, we want to change the plus sign into a minus sign. Finally, a slide effect should be triggered when we click an item. Here's the jQuery code:

$(document).ready(function() {

    $('#menu li:has(ul)').css('list-style-image', 'url(img/plus.gif)');
    $('#menu li:has(ul)').click(function(event) {
  if(this == event.target) {
      if($(this).children().is(':hidden')) {
          $(this).css('list-style-image', 'url(img/minus.gif)').children().slideDown();
      }  else {
          $(this).css('list-style-image', 'url(img/plus.gif)').children().slideUp();
 return false;
        }).css('cursor', 'pointer');
        $('#menu li:not(:has(ul))').css({'cursor': 'default', 'list-style-image':'none'});

We first add an image to all items that contains a list. The list has been hidden with CSS. On each item, we trigger a click event and we target that event only to the items that actually contain a list. If an item contains an hidden list, we show it with the slideDown method. Otherwise, we add a plus sign to the item and we hide the list with the slideUp method. If an item doesn't contain an hidden list, we remove any image from it.

You can see the final result here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.