A blog about PHP, Ajax, JavaScript, CSS and Web 2.0

Making accordion menu using jquery

Last time, I’ve shown how to create accordion using jquery. But, In this post I’ll show you how can you create fancy accordion menu using jQuery. In this post, you’ll see two examples of accordion. First menu’s visibility get’s toggled on clicking on the header while the another menu’s visibility get’s toogled when mouse is moved over it.

As you can see the structure, the elements of the menu are inside the div with class “menu_list”. And each blocks of menu contains the header with class “menu_head” and div with class “menu_body”. Note that, there is another pane with the id “secondpane” whose code is similar as above and not posted above.

I’m not a good color chooser so please forgive me for the color combinations. Above CSS code is straight forward and you can change is according to your need. Note that, the display property in “menu_body” is set to “hidden” so that the menu links are hidden when the page is loaded. Furthermore, the display property in the link inside “menu_body” class is set to “block” so that each menu appears in new line. You can see a image in the “menu_head” class, this is the image which gets changes with the visibility of the menu item in each menu’s head.

Javascript Code using jQuery

And, then we need to write few lines of simple code in jQuery to do this, let’s look at the jquery code of the first accordion menu whose visibility gets toggled on the mouse click event on each header,

When the paragraph with class “menu_head” inside the element with the id “firstpane” gets clicked, the background image of it changed to down arrow. And then, next div with class “menu_body” gets slided in toggling it’s visibility. Furthermore, the other sibling’s div with class “menu_body” gets slided up. And then, the background image of the other sibling’s of “p” is changed to left arrow. Now look at the code of the accordion menu under mouse over effect.

//slides the element with class "menu_body" when mouse is over the paragraph
$("#secondpane p.menu_head").mouseover(function()
{
$(this).css({backgroundImage:"url(down.png)"}).next("div.menu_body").slideDown(500).siblings("div.menu_body").slideUp("slow");
$(this).siblings().css({backgroundImage:"url(left.png)"});
});

This code is preety similar to the above code but the difference is only that this accordion menu works on the mouse over effect whereas the above accordion menu works on the mouse click event.

202 thoughts on “Making accordion menu using jquery”

Comment navigation

my problem is the same as a couple others, i am trying to keep the menu open when the user clicks to a sub page. I am looking to keep the menu open on the sub pages so the user doesn’t have to re click the menu each time a new pages reloads. Redsonic posted some code way above in the comments, but i really don’t know how to implement it. Can someone help?