20 September, 2010

Collapsible Menu using jQuery

Displaying all information at once to a user is not a good idea. Instead data can
be presented to user as chunks, if it can be said. A good example of displaying
only some data at a time collapsible list. In the following section, i am building
a show/hide list, a collapsible list using jquery.

We will be implementing a list items that contain child lists, and at the beginning
the child lists are hidden, and can be collapsible.

In following html, we can see that List Item 3 has content; so its child list elements
are hidden and mouse cursor changes to hand when hovered. I will explain each section
and then provide a complete working javascript code for collapsible list using jquery.

Select all the LI list items that have list children elements and add click event
handler. The click event handler checks if the target elment of event matches this.

$("li:has(ul)").click(function(event) {
....

When a parent list item in clicked the we check that if its children are hidden by
using jquery is() function.

if ($(this).children().is(':hidden')) {
.....

If the children are hidden, then we show them using show() function, and if they are
already shown we make them hidden by using hide() function. So this makes the list
collapsible. Return false is done to avoid needless propagation.

$(this).children().show();
.....
$(this).children().hide();
...
return false;

Then we change the cursor to pointer and add a click handler to our outermost list
item.

.css('cursor', 'pointer')
.click();
......

The last line makes sure that cursor for those li list items that do not have ul lists
will be default and no image will be added to those lists.

$('li:not(:has(ul))').css({cursor: 'default','list-style-image': 'none'});

So this completes our collapsible list using jquery. Furthermore, more css styles
can be added and more jquery features to make it look better.
Following section has complete code for implementation of collapsible menu in jquery.

//head tag start
//include jquery.js script
//script tag start
$(document).ready(function() {
$('li:has(ul)').click(function(event) {
if(this == event.target) {
if($(this).children().is(':hidden')) {
$(this).children().show();
}
else {
$(this).children().hide();
}
}
return false;
})
.css('cursor', 'pointer')
.click();
$('li:not(:has(ul))').css({cursor: 'default','list-style-image': 'none'});
});
//script tag end
//head tag close


  • Item 1

  • Item 2


  • Item 3

    • Item 3.1


    • Item 3.2

      • Item 3.2.1

      • Item 3.2.2

      • Item 3.2.3



    • Item 3.3





No comments: