How to make accordion menu using jquery

Posted on June 1, 2008 
Filed Under ajax, how-to, htaccess, jquery, tips and technique, tutorial

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.

Live Demo of accordion menu using jQuery

HTML structure for accordion menu using jQuery

<div id="firstpane" class="menu_list">
  <p class="menu_head">Header-1</p>
    <div class="menu_body">
	<a href="#">Link-1</a>
    </div>
  <p class="menu_head">Header-2</p>
    <div class="menu_body">
	<a href="#">Link-1</a>
    </div>
  <p class="menu_head">Header-3</p>
    <div class="menu_body">
        <a href="#">Link-1</a>
   </div>
</div>

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.

CSS code for accordion menu using jQuery

.menu_list {
	width: 150px;
}
.menu_head {
	padding: 5px 10px;
	cursor: pointer;
	position: relative;
	margin:1px;
       font-weight:bold;
       background: #eef4d3 url(left.png) center right no-repeat;
}
.menu_body {
	display:none;
}
.menu_body a {
  display:block;
  color:#006699;
  background-color:#EFEFEF;
  padding-left:10px;
  font-weight:bold;
  text-decoration:none;
}
.menu_body a:hover {
  color: #000000;
  text-decoration:underline;
}

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.

I’ve used the images from sweetie icon pack, you can download the other beautiful icon from the their website.

Javascript Code using jQuery

Now finally look at the JavaScript code to accomplish this, first of we need to import the jQuery library

<script type="text/javascript" language="javascript" src="jquery.js"></script>

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,

//slides the element with class "menu_body" when paragraph with class "menu_head" is clicked
$("#firstpane p.menu_head").click(function()
{
    $(this).css({backgroundImage:"url(down.png)"}).next("div.menu_body").slideToggle(300).siblings("div.menu_body").slideUp("slow");
    $(this).siblings().css({backgroundImage:"url(left.png)"});
});

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.

Download Source Code

Popularity: 50% [?]

Enter your email address and get recent tutorials, tips, tricks and scripts of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

Follow me on twitter at http://twitter.com/roshanbh.

Related Posts

» Help me to become the first Blogging Idol
» How to disable context menu in browsers ?
» How to make accordion using jquery and css
» Jquery : Benefits, Examples and Free Ebook

Comments

54 Responses to “How to make accordion menu using jquery”

  1. How to make accordion menu using jquery on June 1st, 2008 10:28 am

    [...] teenagers wrote an interesting post today onHere’s a quick excerptLast 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 … [...]

  2. Steve Mulder on June 2nd, 2008 11:10 am

    What I particularly like about these accordions is that they don’t force the content below to drop down. In other words, everything keeps its place. That is how an accordion should work. Very nice, Roshan.

  3. Roshan on June 2nd, 2008 12:03 pm

    Thanks steve

  4. links for 2008-06-02 | Mior Muhammad Zaki on June 2nd, 2008 12:31 pm

    [...] Create accordion menu using jquery (tags: javascript ajax jquery) [...]

  5. How to make accordion menu using jquery on June 2nd, 2008 4:43 pm
  6. Katod’un Seyir Defteri - 02.06.2008 at katodivaihe on June 2nd, 2008 6:32 pm

    [...] Colony Optimization for TSP in Erlang - SQL Server Programming Hacks - Using URL Rewrite Module - How to make accordion menu using jquery - JavaScript Information Visualization Toolkit [...]

  7. sandra on June 3rd, 2008 8:29 am

    Hey Good one!

  8. Baz L on June 3rd, 2008 6:02 pm

    Now, I’m confused.

    So if this is two lines of code, why is there an entire accordion plugin for jQuery?

    Well, ThanX for that!

  9. Roshan on June 4th, 2008 4:41 am

    hey Baz..thanks for this it’s upto you what to use the plugin or the small piece of code .. this is just a simple piece of accordion menu..the other plugin might have other facility with them I think..

  10. The Abarentos Narrative » links for 2008-06-04 on June 4th, 2008 11:30 pm

    [...] Create accordion menu using jquery (tags: jquery javascript menu accordion ajax navigation ui) [...]

  11. Abs on June 8th, 2008 4:12 pm

    Hi Roshan,

    This is excellent! If I wanted Header-2 to be opened as standard (before it is clicked), is this possible?

    Many Thanks.

    Keep up the good work!

  12. Roshan on June 8th, 2008 4:40 pm

    you can use jquery’s selector to do this such as..

    $(’.menu_body:eq(2)’).show();

    to do this

  13. Abs on June 8th, 2008 7:52 pm

    Thanks Roshan, that works brilliantly!

  14. Fatih Hayrio?lu'nun not defteri » 09 Haziran 2008 web’den seçme haberler » Html, nas?l, kodlan?r, Ba?lant?, Sitelerde, çok, kullan?yoruz, Buda, baz?, yava?lamalar on June 9th, 2008 8:22 am

    [...] jQuery ile akordiyon menü yap?m?n? makalesi. Ba?lant? [...]

  15. Abs on June 10th, 2008 7:10 pm

    Hi Roshan,

    Do you know if I can colour the selected menu_head in a different background colour to differentiate it from the rest that are not selected?

    Thanks

    Abs

  16. Omar on June 10th, 2008 10:20 pm

    Can you control the menu so that when you follow a link the menu stays open?

  17. Roshan on June 11th, 2008 4:21 am

    @abs - yes you can use the css property for this

    $(this).css({backgroundImage:”url(down.png)”})
    can be replaced with
    $(this).css({backgroundImage:”url(down.png),backgroundColor:”#cccccc”"}).

    @omar - for that you need to store the data in cookie or have to use ajax and save the state in database

  18. Obistyle on June 13th, 2008 6:07 pm

    I like to know how i can make the first menu item active?

    Simular question has already been asked by Abs, but i don’t understand the answer of Roshan…

    “you can use jquery’s selector to do this such as.
    $(’.menu_body:eq(2)’).show();
    to do this”

    I don’t know where to put that code.

    Please help!

  19. Roshan on June 14th, 2008 3:12 pm

    well you can put the following code like this

    $(document).ready(function()
    {
    $(’.menu_body:eq(0)’).show();

  20. Obistyle on June 16th, 2008 7:55 am

    Thank you. It works!

    Only thing is that you have to use double quotes instead of single quote.

  21. rossco on June 23rd, 2008 12:00 pm

    Hello, I like the roll-over effect for the accordion… looks great. I have an ajax search function on my site that uses mootools 1.11 and I’ve tried a mootools and another jquery accordion but both are conflicting with the search. I was wondering if you have tested your accordion with other libraries or if you have an idea of how to make it work with mootools? I have tried the simple no conflict line for jquery but this didn’t help with the other accordion menu I tried. I’m no programmer so if you have any info that would be super. Thanks!

  22. rossco on June 23rd, 2008 12:54 pm

    Ok update… I managed to get the mootools and jquery library working together just fine. What I would like to know is how I can keep each accordion open when each is click and only have them shut when they are clicked when already expanded? Is this possible?

    Great work

  23. rossco on June 23rd, 2008 1:04 pm

    Sorry, I totally forgot to add a question! Forgive the spam lol.

    I was wondering how I could make the first pane load being extended already? So people can see the options on display for that page?

  24. Roshan on June 23rd, 2008 3:56 pm

    rossco..you’ve to use ajax to make the accordion still to be opened when the link is clicked and you can see the answers in the comment above to see how can you make first pane load being extended already….

    please read the comment above carefully….

  25. rossco on June 23rd, 2008 4:26 pm

    Thanks for the prompt reply… I have this as my code. Bear in mind i’m using the no conflict idea for jquery.

    var $j = jQuery.noConflict();
    $j(document).ready(function()
    {
    $j(’.menu_body:eq(0)’).show();
    {
    //slides the element with class “menu_body” when paragraph with class “menu_head” is clicked
    $j(”#firstpane p.menu_head”).click(function()
    {
    $j(this).css({}).next(”div.menu_body”).slideToggle(300).siblings(”div.menu_body”).slideUp(”slow”);
    $j(this).siblings().css({});
    });
    //slides the element with class “menu_body” when mouse is over the paragraph
    $j(”#secondpane p.menu_head”).mouseover(function()
    {
    $j(this).css({}).next(”div.menu_body”).slideDown(500).siblings(”div.menu_body”).slideUp(”slow”);
    $j(this).siblings().css({});
    });
    });

    This didn’t work. Any help would be great. Thanks.

  26. rossco on June 23rd, 2008 4:44 pm

    I’m an idiot, ok. I managed to get it working!

    I understand that you change the number in the () to represent which area to leave open. I’m using this accordion as a menu, could you write up a tut on how to either use a cookie or ajax so the menu knows which part to leave extended?

    You can delete my above post if you wish. lol
    Thanks

  27. Roshan on June 23rd, 2008 6:20 pm

    Hi rossco, I’ll post how to use this menu with ajax as soon I get the time…

  28. PJ on June 24th, 2008 9:03 pm

    Roshan,

    Thank you for such an easy to use menu utility. I’ve added it to my page and it works great. I do have one question (need help): how can I update the code (what do I need to change) so that the menu goes away (hides) when the mouse is moved away from the menu? Currently the menu comes up okay, but it stays up when I go to other places in the page.

    Thank you,

    PJ

  29. Help me to become the first Blogging Idol on July 1st, 2008 5:33 pm

    [...] State Preserved Accordion menu using jQuery (Last time I’ve posted how to create accordion menu using jQuery but State was not preserved in that example) [...]

  30. Carol Deckelbaum on July 3rd, 2008 8:39 pm

    My question is similar to Abs - I now understand how to force a pane to be open, but how can I keep it open even when one of the other main menu heads are clicked?

    Thanks,
    Carol

  31. Roshan on July 4th, 2008 4:45 am

    @carol - why don’t you check the following link for that …

    roshanbh.com.np/2008/03/expandable-collapsible-toggle-pane-jquery.html

  32. Dave on July 21st, 2008 12:35 pm

    I’ve got the accordion working fine with the first pane opening when the page loads. I can’t seem to get the left/down icon to be correct on the first opening pane. It has the left icon showing where the down should be. After a few clicks the first pane toggles correctly, but is flipped (left/down icons) because the first pane is already open.
    How do I get first open pane (Icon) when the page loads to have the down arrow show instead of the default left?

  33. Roshan on July 22nd, 2008 4:58 pm

    $(this).css({backgroundImage:”url(down.png)”})

    that css function changes the background image…you can check the jquery documentation for detail information…

  34. Dave on July 23rd, 2008 6:01 pm

    $(document).ready(function()
    {
    $(”.menu_body:eq(0)”).show();
    //slides the element with class “menu_body” when paragraph with class “menu_head” is clicked
    $(”#firstpane p.menu_head”).click(function()
    {
    $(this).css({backgroundImage:”url(down.png)”}).next(”div.menu_body”)
    .slideToggle(300).siblings(”div.menu_body”).slideUp(”slow”);
    $(this).siblings().css({backgroundImage:”url(left.png)”});
    });
    });

    This is the code that I have on my site. It has the first pane open when the page loads, but the arrow for the first pane is pointing left instead of down. Any ideas of how can I get the arrow pointing down on the first pane when a page first loads. It seems when you click on the other toggle header panes the arrows will correct themselves, but that first page load and the open toggle icon will always point left instead of down. Any ideas of how to correct that first pane from loading the left arrow?

  35. Roshan on July 23rd, 2008 7:10 pm

    $(”.menu_body:eq(0)”).show();
    after that add this line..
    $(”.menu_head:eq(0)”).css({backgroundImage:”url(down.png)”})

  36. Dave on July 23rd, 2008 7:25 pm

    Thanks Roshan, That bit of code worked great.

  37. Peter on July 29th, 2008 8:18 am

    Great Job: I´ve a firstpane, with “menu_head”, a secondpane with class “menu_body” but how can I open a thirdpane bellow Link-2 or Link-3? Thank you very much

  38. Peter on July 29th, 2008 5:25 pm

    Sorry: I´d like to say a “thirdpane after Link-1, Link-2 or Link-3. Thank you very much

  39. Manish Patel on July 29th, 2008 7:08 pm

    Hi
    I am trying build accordion menu using jquery. it works fine on Firefox PC but, but on ie accordion didn’t collapsed it self, you have to click again on same link, otherwise it open all accordion.

    I am also testing on Safari and Firefox on Mac, when i click on accordion it doesn’t expand. If i clicked few times it works. If anybody have idea about this kind of bug please help me.

    I hope you will find solution.
    Thanks Roshan

    Manish

  40. Roshan on July 30th, 2008 4:25 am

    @peter - I’ve already told the answer above but here the answer again…put the following code

    $(document).ready(function()
    {
    $(’.menu_body:eq(0)’).show();

    where 0 for first pane, 1 for second and 2 for third pane..

    @Manish - if you download the code and run in internet explorer, it is running perfectly without any problem …

  41. Peter on July 30th, 2008 10:20 am

    HEADER-1
    **Link-1
    **Link-2
    ******Link-a
    ******Link-b
    ******Link-c
    **Link-3
    HEADER-2
    HEADER-3

  42. Manish on July 30th, 2008 8:06 pm

    Thanks Roshan

    Its works now, but i have issue on Mac safari 2.0, when i click first time on accordion it don’t expand but if i click on another accordion and the it expand. it works fine on Mac safari 3.0.

    Thanks

    Manish

  43. tristen on August 11th, 2008 8:27 pm

    Hey Roshan

    Thanks for this. And your long list of answers to comments.

    I’m stuck on implementing this in Drupal and wonder if you have a quick solution for it.

    I’m entering in the following code:

    What am I missing to get this to work?
    I get the following error:

    Parse error: syntax error, unexpected ‘(’, expecting T_VARIABLE or ‘$’ in E:\”path”\includes\common.inc(1355) : eval()’d code on line 3

  44. tristen on August 11th, 2008 8:30 pm

    Ahhh … no php? sorry for the spam

    Whoops! Guess I missed the jquery code.
    It’s this:

    drupal_add_js(

    $(document).ready(function(){
    $(”.menu_body:eq(0)”).show();
    $(”.menu_head:eq(0)”).css({backgroundImage:”url(pathtoimage/down.png)”})

    $(”#firstpane p.menu_head”).click(function(){
    $(this).css({backgroundImage:”url(pathtoimage/down.png)”})

    .next(”div.menu_body”)
    .slideToggle(300).siblings(”div.menu_body”).slideUp(”slow”);
    $(this).siblings().css({backgroundImage:”url(pathtoimage/left.png)”});
    });

  45. Roshan on August 12th, 2008 5:18 pm

    @tristen- seems that you’re having the eval() of PHP with the “$” sing of jquery library.

    try isng jquery instead of $ in above code like
    “jQuery(document).ready” .. hope it helps

  46. tristen on August 14th, 2008 3:05 am

    Thanks Roshan!

    I started thinking about that and the trick was to wrap the jquery with ‘

    (php starts)

    drupal_add_js(

    jquery goes here.

    ‘inline’
    );

    (php ends)

  47. deep on August 14th, 2008 11:37 am

    Hi Roshan,
    This is a good piece of code. I shall be adding it to http://www.downloadjavascripts.com.

  48. Christian Philippsen on August 20th, 2008 6:27 am

    Oh, i would love this accordion menu in a underordered list.

  49. Roshan on August 20th, 2008 9:13 am

    @christian - yes that would have been the better if I would have have used unordered list in this accordion menu

  50. Christian Philippsen on August 20th, 2008 12:09 pm

    @roshan - oh typo, yes it was of course a unordered list I referred to :)

    It sure would have been more easy for integration in a CMS like Joomla. Otherwise great script.

  51. Bryson Justus on August 27th, 2008 7:47 pm

    If you click on Header-1 to open a section then click Header-1 to close the section the arrow doesn’t change back. How do you fix that?

  52. Roshan on August 28th, 2008 5:15 am

    @Bryson - Thanks for mentioning the bug, Let me fix that post that soon…

  53. Dude on September 2nd, 2008 8:48 pm

    I want to be able to add pictures and tables within each accordion rather than tages

    When i simply put text its getting left.png file to show on top of the text why ?

    can you please show me a sample of adding normal text instead of li inside the accordion

    thanks mate

  54. Sarah on September 4th, 2008 6:07 pm

    For the rollover version of the menu how do you change the code so that when the user moves the mouse off the menu collapses? I’d like to have all menus closed unless the user is hovering over one item.

Leave a Reply