Jquery Accordion menu with active states

This is an old post that I saved from my old blog which has unfortunately been lost somewhere amidst the interwebs, (thanks Yahoo.) That's what I get for being young and registering domains with Yahoo, oh well, lesson learned :)

View The Demo

I was recently given the task of creating an accordion type menu that would also have active states to allow for a changing icon based on what menu item you clicked on. I did some research and found there was in fact a Jquery accordion menu plugin. However, this tutorial doesn't use any plugins or extra "stuff". Just your standard Jquery.js file is all you need. If you're working on a Drupal6.x site you don't even need to worry about that as Drupal comes with Jquery now! :)

So let's get started! This is a pretty simple build all things considered! You achieve really great looking results with just a few lines of code. To prove it, here's our code: (this would be placed before the

tag of an html file)
<script type="text/javascript" src="http://jquery.com/src/jquery.js">
</script>
<script type="text/javascript">
$(function(){
$("ul li ul.options").hide();
$("ul.options:not(:first)").hide();
$("a.click").click(function(){
$("ul li.menu-item").removeClass("active");
$(this).parent().addClass("active");
$("ul li.menu-item ul.options").slideUp("slow");
$(this).parent().children().slideDown("slow");
return false;
});
});
</script> <style type="text/css">

Not too shabby eh? Now take a look at the results.

To get this working really all you need to do is set up your list correctly. For our example we using a nested list. Looks like this:

<ul>
<li class="menu-item"><a class="click" href="/">Menu Item 1</a>
<ul class="options">
<li>option 1</li>
<li>option 2 is cool</li>
<li>option 3</li>
</ul>
</li>
</ul>
<ul>
<li class="menu-item"><a class="click" href="/">Menu Item 2</a>
<ul class="options">
<li>option 1</li>
<li>option 2</li>
<li>option 3 is da bomb</li>
</ul>
</li>
</ul>
<ul>
<li class="menu-item"><a class="click" href="/">Menu Item 3</a>
<ul class="options">
<li>option 1 isn't this fun!?</li>
<li>option 2</li>
<li>option 3</li>
</ul>
</li>
</ul>

The big thing to remember here is that you need a way to distinguish your parent lists from your child lists.
So here we're using classes. The parent li items have a class of "menu-item" and the child ul's have a class of "options". You'll also want to distinguish between the links that are your parent menu items and if you have any links in your child lists.

This example isn't using links in the child lists but I went ahead and gave the parent links a class of "click" anyway. You can make your class names whatever you want, just be sure to change the jquery code to reflect your own class names or id's.

Once you get that working the rest is just CSS! Take a look at the Source Code of the Demo Page to see exactly what I did to get mine working and looking the way it does. Let me know if you have questions or comments!!!