Simple accordion menu using JQuery

I’m anti-talent at programming but it seems I never give up :slight_smile:

Anyway, I want to accomplish a nice and simple accordion menu using this HTML structure:

<ul id="sidenav">
	<li><a href="#">Menu 1</a>
    	<ul>
        	<li><a href="#">Submenu 1</a>
            <li><a href="#">Submenu 2</a>
            <li><a href="#">Submenu 3</a>
        </ul>
    </li>

    <li><a href="#">Menu 2</a>
    	<ul>
        	<li><a href="#">Submenu 1</a>
            <li><a href="#">Submenu 2</a>
            <li><a href="#">Submenu 3</a>
        </ul>
    </li>

    <li><a href="#">Menu 3</a>
    	<ul>
        	<li><a href="#">Submenu 1</a>
            <li><a href="#">Submenu 2</a>
            <li><a href="#">Submenu 3</a>
        </ul>
    </li>
</ul>	

And I’m using this JQuery code:

$(document).ready(function() {
	$('#sidenav > li > ul:gt(0)').hide();
	
	$('#sidenav > li').click(function(){
		$(this).children('ul').slideDown('slow');
		$('#sidenav > li > ul:visible').slideUp('slow');
	});
});

This basically works, but when I click a particular menu item to expand it’s submenu items, it basically hides all submenus items, even the active ones, but whant I need is the particular clicked submenu items to stay expanded. I guess this can be accomplished by a simple if statement or so. Any ideas?

Try using this for the click function instead…


$ul = $(this).children('li').slideDown('slow');
$('#sidenav > li > ul').not($ul).slideUp('slow');

jQuery also provides an accordion plugin, that takes over most of the hard work for you.

http://docs.jquery.com/UI/Accordion

Yuhuu it works. I only changed this “children(‘li’)” into this “children(‘ul’)” and it worked.

Later on I’ll see how the accordion plugin works too.