jQuery in Action
Showing and hiding elements
131
We can see that for the list items that have content (items 3 and 4) the follow-
ing occurs:
ing occurs:
The children of the list items 3 and 4 are hidden.
The list markers for the items have been replaced with a plus-sign graphic
to indicate that the item can be expanded.
to indicate that the item can be expanded.
The mouse cursor changes to the hand when it hovers over these items.
Clicking these active items reveals their children as shown in the series of displays
in figure 5.3.
in figure 5.3.
Let's examine how we apply this behavior to the
DOM
elements of the list, set-
ting it up within the ready handler, as shown in listing 5.1.
$(function(){
$('li:has(ul)')
.click(function(event){
if (this == event.target) {
if ($(this).children().is(':hidden')) {
$(this)
.css('list-style-image','url(minus.gif)')
.children().show();
} else {
$(this)
.css('list-style-image','url(plus.gif)')
.children().hide();
}
}
return false;
})
Listing 5.1 Ready-handler code that instruments the list with expandable behavior
Figure 5.2 After instrumentation, the list has been fully collapsed and the expandable
items are visually distinct.
items are visually distinct.
b
c
d
e