Write your own jQuery accordions in 7 lines of code.

A lot of times, people want very specific functionality out of a jquery menu. There are at least 5 or 6 decent jQuery accordion menu plugins out there. But they're all overkill in my opinion.

A jQuery accordion can be as little as 3 lines of code. Here's one in 7 lines of code. And if you do some chaining, probably even less.

$('#accordion li ul').hide();
$('#accordion li a').click(function(){
	$(this).parent().addClass('selected');
	$(this).parent().children('ul').show('fast');
	$(this).parent().siblings().children('ul').hide('fast');
	$(this).parent().siblings().removeClass('selected');	
});

So how does this work? The first command hides all the sub-menus. Then you add a click listener to the item itself. When you click it, you add a "selected" class to its parent list element. That way you can style it appropriately if it is selected. Then you show the sub menu on the next line. Finally, hide all the siblings and remove their selected classes. Now, assuming you've got the CSS, XHTML structure in place... that's it. You are done my friend.

<ul id="accordion">
    <li><a>Item</a>
        <ul>
			<li><a href="#">sub item</a></li>
			<li><a href="#">sub item 2</a></li>
			<li><a href="#">sub item 3</a></li>
		</ul>
    </li>
	<li><a>Item 2</a>
        <ul>
			<li><a href="#">sub item</a></li>
			<li><a href="#">sub item 2</a></li>
			<li><a href="#">sub item 3</a></li>
		</ul>
    </li>
	<li><a>Item 3</a>
        <ul>
			<li><a href="#">sub item</a></li>
			<li><a href="#">sub item 2</a></li>
			<li><a href="#">sub item 3</a></li>
		</ul>
    </li>
</ul>

Very basic nested list elements.

Now let's add some CSS.

#accordion li a{cursor:pointer;text-decoration:none;}
#accordion li.selected {font-weight:bold;}

Here's a demo.