Expandable Trees
jQuery Novice to Ninja 8.4 (page 305)
by beej
HTML
<ul id="celebTree">
<li><span>A-list Celebreties</span>
<ul>
<li><span>In a successful band</span>
<ul>
<li>Johnny Stardust</li>
<li>Glendatronix</li>
</ul>
</li>
<li><span>Famous because they're rich</span>
<ul>
<li>Zucky Suck</li>
<li>Bim Smardashian</li>
</ul>
</li>
</ul>
</li>
</ul>
CSS
.handle {
display: block;
float: left;
width: 10px;
height: 10px;
cursor: pointer;
}
.closed { background-position: left top;}
.opened { background-position: left - 10px;}
.sprite {
text-decoration: none;
color: blue;
font-weight: 700;
}
#celebTree ul li {
margin-left: 30px;
}
JavaScript
$("#celebTree ul")
.hide()
.prev('span')
.before('<span class="sprite">+</span>')
.prev()
.addClass('handle closed')
.click(function(event) {
$(this)
.toggleClass('closed opened')
.nextAll('ul')
.toggle();
$(this).text( ($(this).text() === '+') ? '-' : '+');
});