Helping ordinary people create extraordinary websites!

Five Ways to Spice Up Your Site with jQuery

By Akash Mehta
2008-11-05

Tip 3: Building a simple collapsing menu

With a lot of menu options on a sidebar, it's always handy to be able to hide inactive menus. Using jQuery, we can create simple collapsing/expanding menus, and even quick and easy accordions!

Let's say we've got a menu similar to this:

<ul id="menu">
<li>
<a href="#">Users</a>

<ul>
<li><a href="#">View</a></li>
<li><a href="#">Edit</a></li>
<li><a href="#">Manage</a></li>
</ul>
</li>
<li>
<a href="#">Resources</a>

<ul>
<li><a href="#">View</a></li>
<li><a href="#">Edit</a></li>
<li><a href="#">Manage</a></li>
</ul>
</li>
</ul>

Here we have a simple unordered list, which we can transform into a simple collapsing/expanding menu with just a few lines of jQuery. Inside $(document).ready(), we could add the following:

$("#menu ul").hide();
$("#menu li a").click(function(){
$(this).next().toggle();
}

And we're done! The first line hides all lists inside the <ul id="menu"> - that is, it selects the submenus and removes them from view. Whenever we click one of the links, we move to the next element - a <ul> of a submenu - and toggle its visibility status. A demo is available here.





Tutorial pages:
 2 Votes

You might also want to check these out:


Leave a Comment on "Five Ways to Spice Up Your Site with jQuery"
You must be logged in to post a comment.

Link to This Tutorial Page!


GET OUR NEWSLETTERS