Themeforest

jQuery Simple Vertical Accordion Menu

Today’s jQuery tutorial is a perfect example of how easy it is to add a slick vertical accordion style menu to your website with just a few lines of jQuery code!

The HTML

First we create a nested unordered list, which will include all of our links. Give the first ul tag a unique id – we use #nav:

<ul id="nav">
  <li><a href="#">Item 1</a>
    <ul>
      <li><a href="#">Sub-Item 1 a</a></li>
      <li><a href="#">Sub-Item 1 b</a></li>
      <li><a href="#">Sub-Item 1 c</a></li>
    </ul>
  </li>
  <li><a href="#">Item 2</a>
    <ul>
      <li><a href="#">Sub-Item 2 a</a></li>
      <li><a href="#">Sub-Item 2 b</a></li>
    </ul>
  </li>
  <li><a href="#">Item 3</a>
    <ul>
      <li><a href="#">Sub-Item 3 a</a></li>
      <li><a href="#">Sub-Item 3 b</a></li>
      <li><a href="#">Sub-Item 3 c</a></li>
      <li><a href="#">Sub-Item 3 d</a></li>
    </ul>
  </li>
  <li><a href="#">Item 4</a>
    <ul>
      <li><a href="#">Sub-Item 4 a</a></li>
      <li><a href="#">Sub-Item 4 b</a></li>
      <li><a href="#">Sub-Item 4 c</a></li>
    </ul>
  </li>
</ul>

Style The Menu With CSS

For this tutorial we add a little styling to the menu and use CSS to hide the sub-menus using “display: none;”:

#nav {float: left; width: 280px;  border-top: 1px solid #999; border-right: 1px solid #999; border-left: 1px solid #999;}
#nav li a {display: block; padding: 10px 15px; background: #ccc; border-top: 1px solid #eee; border-bottom: 1px solid #999; text-decoration: none; color: #000;}
#nav li a:hover, #nav li a.active {background: #999; color: #fff;}
#nav li ul {display: none;}
#nav li ul li a {padding: 10px 25px; background: #ececec; border-bottom: 1px dotted #ccc;}

The jQuery Code

To create the accordion effect the code is extremely simple:

$(document).ready(function () {
  $('#nav > li > a').click(function(){
    if ($(this).attr('class') != 'active'){
      $('#nav li ul').slideUp();
      $(this).next().slideToggle();
      $('#nav li a').removeClass('active');
      $(this).addClass('active');
    }
  });
});

First we use the child selector “>” to ensure that only the parent links activate the accordion menu – otherwise you would end up closing the menu each time a sub-link is clicked.

We add a new class to the active item – this allows us to not only style the open accordion menu but also identify if a sub-menu is open when a link is clicked. The above jQuery code will only work on closed menu items.

View the jQuery vertical accordion menu demo.

Update 5th Mar 2011:

We have now also released the jQuery Vertical Accordion Menu Plugin, which makes it easy to create accordion menus from any nested HTML lists. The plugin has several features including use of cookies and ability to select either hover or click to activate the menu.

Check out the project pages for more information and examples or go straight to the download page.

127 Comments

  • Lee, this is all my code i´m new qith the jquery

    <!-- InstanceBegin template="/Templates/samara_beach1.dwt" codeOutsideHTMLIsLocked="false" -->
    
    <!-- InstanceBeginEditable name="doctitle" -->
    Arenal Volcano Tour -SAMARA BEACH VACATION TOUR GUANACASTE COSTA RICA
    
    			google.load("jquery", "1.3");
    
    <!-- InstanceEndEditable -->
    
    	Simple JQuery Accordion menu - Version 3
    	<!--[if lt IE 9]&gt;-->
    
       li a {display:inline-block;}
       li a {display:block;}
    
    <!-- InstanceBeginEditable name="head" -->
    <!-- InstanceEndEditable -->
    
    		<!-- InstanceBeginEditable name="head2" --><!-- InstanceEndEditable -->
    
                &nbsp;
    
                   <a href="../index.html" rel="nofollow">HOME</a>
                   <a href="#" rel="nofollow">SAMARA BEACH</a>
    
                        <a href="../samara_beach_location_guanacaste.html" rel="nofollow">Samara Beach Information</a>
                        <a href="../samara_beach_tours_guanacaste.html" rel="nofollow">Samara Beach Tours</a>
                        <a href="../samara_beach_hotels_guanacaste.html" rel="nofollow">Samara Beach Hotels</a>
                        <a href="../samara_beach_transportation_guanacaste.html" rel="nofollow">Samara Beach Transportation</a>
                        <a href="../samara_beach_map_guanacaste.html" rel="nofollow">Samara Beach Map</a>
    
                   <a href="#" rel="nofollow">MONTEVERDE CLOUDFOREST</a>
    
                        <a href="../monteverde_samara_beach_location.html" rel="nofollow">Monteverde Information</a>
                        <a href="../monteverde_samara_beach_tours.html" rel="nofollow">Samara Beach Tours</a>
                        <a href="../monteverde_samara_beach_hotels.html" rel="nofollow">Samara Beach Hotels</a>
                        <a href="../monteverde_samara_beach_transportation.html" rel="nofollow">Samara Beach Transportation</a>
                        <a href="../monteverde_samara_beach_map.html" rel="nofollow">Samara Beach Map</a>
    
                   <a href="#" rel="nofollow">ARENAL VOLCANO</a>
    
                        <a href="../arenal_volcano_location_samara_beach.html" rel="nofollow">Arenal Volcano Information</a>
                        <a href="../arenal_volcano_tours_samara_beach.html" rel="nofollow">Arenal Volcano Tours</a>
                        <a href="../arenal_volcano_hotels_samara_beach.html" rel="nofollow">Arenal Volcano Hotels</a>
                        <a href="../arenal_volcano_transportation_samara_beach.html" rel="nofollow">Arenal Volcano Transportation</a>
                        <a href="../arenal_volcano_map_samara_beach.html" rel="nofollow">Arenal Volcano Map</a>
    
                   <a href="#" rel="nofollow">VACATION PACKAGES</a>
    
                        <a href="../samara_beach_package1.html" rel="nofollow">Packages Skynet 1</a>
                        <a href="../samara_beach_package2.html" rel="nofollow">Packages Skynet 2</a>
                        <a href="../samara_beach_package3.html" rel="nofollow">Packages Skynet 3</a>
                        <a href="../samara_beach_package4.html" rel="nofollow">Packages Skynet 4</a>
    
                 <a href="../samara_beach_skynet.html" rel="nofollow">ABOUT US</a>
                 <a href="../reserve_samara_beach.html" rel="nofollow">RESERVATIONS</a>
                 <a href="../site_map_samara_beach.html" rel="nofollow">SITE MAP</a>
    
                  <!-- InstanceBeginEditable name="contenidos" -->
                    Arenal Volcano Tour  - SAMARA BEACH VACATION TOUR GUANACASTE COSTA RICA
    
                        <a href="../samara_beach_tours_guanacaste.html" rel="nofollow">Back Samara Beach Tour List</a> | Reserve this tour
    
                        <strong>The amazing Arenal Volcano!</strong> This Volcano is one of the world's most  spectacular volcanoes. In addition to huge ash columns and eruptions of glowing  rock, the volcano occasionally sets off pyroclastic avalanches- a dramatic flow  of fast moving hot gas and rock. Another great benefit of this volcano is the  natural geothermal heat that warms groundwater and creates natural hot springs.  The hot springs are an ideal way to relax after a day full of adventure.
    
                        <strong>&#8226; What  to bring:</strong> Hiking Shoes, rain coat, swimming suit, towel, camera and insect  repellent.<strong>
    
    </strong><strong>&#8226; What&rsquo;s  included?:</strong>
    Transport in A/C minivan, breakfast, lunch, entrance fee to Baldi hot springs and Fortuna waterfall,  drinks and experienced guide/driver
    
                          <strong>&#8226; Price: </strong>
      $120.00 U.S - 5 persons min
      $135.00 U.S
      - 4 persons min
      $150.00 U.S - 3 persons min
      $185.00 U.S - 2 persons min
    <strong>&#8226; Pick up time:</strong>  6:00am
    <strong>&#8226; Duration:</strong> 14 hours
    
          <strong>&#8226; Tour Photo Gallery:</strong>
    
                 <a href="../images/fullscreen/arenal1b.jpg" rel="nofollow"></a>
                 <a href="../images/fullscreen/arenal2b.jpg" rel="nofollow"></a>
                 <a href="../images/fullscreen/arenal3b.jpg" rel="nofollow"></a>
                 <a href="../images/fullscreen/arenal6b.jpg" rel="nofollow"></a>
                 <a href="../images/fullscreen/arenal5b.jpg" rel="nofollow"></a>
                 <a href="../images/fullscreen/arenal4b.jpg" rel="nofollow"></a>
    
    		$(document).ready(function(){
    			$(".gallery a[rel^='prettyPhoto']").prettyPhoto({theme:'facebook'});
    		});
    
                  &nbsp;
                  &nbsp;
    
                  <!-- InstanceEndEditable -->
    
                &nbsp;
    
    		<strong> Skynet Tours - </strong>Tours, transportation, Monteverde, Arenal Volcano, Samara Beach
    Tel.: (506) 2656-0920 / Fax: (506) 2656-0920 |
          Es<a href="mailto:info@samara-tours.com" rel="nofollow">info@samara-tours.com</a>
          Costa Rica, Guanacaste. Playa Samara &reg;
    
    <!-- InstanceEnd -->
    
    • Hi Juanz – not sure how the prettyPhoto is related to the menu?

  • Hi Lee may you can helpme i have problem with pretty photo and JQuery Accordion menu. The menu works but the efect of Pretty photo dont work. I´m working in HTML

    • Hi Juanz – do you have a link I can look at? Also is this the WordPress plugin version or just the jQuery plugin?

  • Great thanks!

    I suspected as much with it having the ajax/libs part of the path.

    I can finally move my navigation forward!

  • Hi

    Sorry, silly me, didn’t realise I missed this out of my previous message!

    This is the script I was querying?

    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script&gt;
    

    Sorry if this is stupid question – it’s been quite a while since I did any web coding.

    Thanks again!

    • Hi – yes its the jQuery library. This needs to be placed before any other jQuery plugins or code.

  • Hello,

    After bothering you with a bunch of badly formatted questions in the comment area, I finally found the problem i was having. My nav list was formatted

    [/text] 
    
    [text]

    And so it was wrong! I didn’t spot as my menu and submenu were generated with php, and not very easy to look at.

    Thanks for your help.

  • Hi

    This is exactly what I’ve been looking for! I have found other methods to do this, but the javacript is rather clunky.

    Only one problem, I’m having trouble getting this to work.

    I copied all the code/markup from above exactly (HTML, CSS and jquery), but the menu is not expanding / collapsing when I click the menu items.

    I’ve traced the issue down to my code not including the following scrip – which is present in your markup, I identified this using firebug:

    What is the purpose of this script and is the whole of the script necessary?

    Thanks again!

    • Hi – which script are you refering to?

  • Yes, the links are wrapped in

    [/text][text]

    elements. This is what the browser is getting:

    [/text] 
    
    <a href="#" rel="nofollow">
    
    </a>
    
    <a href="http://localhost:8888/CI/photography/subMenu/genre/Music/client/Sarah Standard" rel="nofollow">Sarah Standard</a>
    
    <a href="http://localhost:8888/CI/photography/subMenu/genre/Music/client/Jamie Lidell" rel="nofollow">Jamie Lidell</a>
    
     [text]
  • OK, this is the php that generates the menu html, and then I will post the view source of the page once it is loaded:

    [/text] data['menu'])) {
             if ($this-&gt;data['main_content'] == 'photography') {
                    $uri_method = '/subMenu/genre/';
                    echo '';
                    foreach($this-&gt;data['menu'] as $menu) {
                            echo '<a href="#" rel="nofollow"></a>';
                            foreach($this-&gt;data['submenu'][$menu] as $submenu) {
                                    echo '<a>data['mai
    n_content'].$uri_method.$menu.'/client/'.$submenu.'"&gt;'.$submenu.'</a>';
                            }
            echo '';
                    }
            echo ' <!-- end of menu ul -->'; [text]

    And

    [/text] <a href="#" rel="nofollow"></a><a href="http://localhost:8888/CI/photography/subMenu/genre/Music/client/Sarah Standard" rel="nofollow">Sarah Standard</a><a href="http://localhost:8888/CI/photography/subMenu/genre/Music/client/Jamie Lidell" rel="nofollow">Jamie Lidell</a><a href="#" rel="nofollow"></a><a href="http://localhost:8888/CI/photography/subMenu/genre/Fashion/client/Jamie Lidell" rel="nofollow">Jamie Lidell</a><a href="#" rel="nofollow"></a><a href="http://localhost:8888/CI/photography/subMenu/genre/Art/client/James van Leuven" rel="nofollow">James van Leuven</a> <!-- end of menu ul --> [text]
    • Hi Leigh, Not sure if Im maybe missing some code … are the links wrapped in

      <li>/<li>

      tags?

  • Yes, I can. Thanks for looking at this, because I am new to javascript and baffled.

    I have this included in the header:

    <script src="prettyPhoto/js/jquery-1.4.4.min.js
    " type="text/javascript">
    <script src="prettyPhoto/js/jquery.prettyPhoto.
    js" type="text/javascript" charset="utf-8">

    $(document).ready(function () {
    $('#menu > li > a').click(function(){
    if ($(this).attr('class') != 'active'){
    $('#menu li ul').slideUp();
    $(this).next().slideToggle();
    $('#menu li a').removeClass('active');
    $(this).addClass('active');
    }
    });
    });

    And my menu is generated by php, and comes out as follows:
    Sarah StandardJamie LidellJamie LidellJames van Leuven

    And finally, here is the css I have, copied also from the demo.
    #menu { float: left; width: 280px; list-style-type: none;}#menu li a {display: block; padding: 10px 15px; background: #ccc; text-decoration: none; color: #000;}
    #menu li a:hover, #menu li a.active {background: #999; color: #fff;}
    #menu li ul { display: none;}
    #menu li ul li a {padding: 10px 25px; background: #ececec; border-bottom: 1px dotted #ccc;}

    Also, firebug show that a clicked-on link in the outer ul is indeed getting marked as active:

    If you have any other questions, please let me know. I would post a link, but it’s just on a dev server on my laptop, not up on line.

    All the best, Leigh

    • Leigh – unfortunately the tags arent showing in the comments – I presume that the menu is made from an unordered list?

    • Leigh – the jQuery code works OK. It may be an issue with the menu HTML. Can you post the HTML but wrap it using

      [text] 

      [/text]

  • Hello Again,

    #nav li ui {display: none} doesn’t work for me. I can hide the submenu items if I write it: #nav ul li { etc, etc, but the other way around, they just remain visible. Also, I still have this situation where I get class=”active” added to the current menu item, but no slide effects.

    Does anyone know what could be causing this discrepancy? I am looking at the source code for the demo, and I can’t see any difference with my code. I tried adding a position:relative to the #nav id and position:absolute for the submenu items, but no luck so far.
    Best, Leigh

    • Can you post/send the source code for the menu?

  • Hello,

    Is there other css at work on these demos, or something that is missing? I followed the tutorial and I just get a menu and sub menu (with bullet list style) and with no jquery effects. Inspecting the elements shows that the correct is getting marked as “active”, so the jquery is working, but the animation effects are not… Any ideas?

    This is my code:
    Sarah StandardJamie LidellJamie LidellJames van Leuven
    $(document).ready(function () {
    $('#menu > li > a').click(function(){
    $('#menu li ul').slideUp();
    if ($(this).next().is(":visible")){
    $(this).next().slideUp();
    } else {
    $(this).next().slideToggle();
    }
    $('#menu ul li a').removeClass('active');
    $(this).addClass('active');
    });
    });

    • Hi Leigh – you need to set the sub-menu to display: none in the CSS:

      #menu li ul {display: none;}

  • Thank you very much Lee, i´t works nice and dandy! I´ll let you know when I got this in production enviroment server..

  • Hi, I´m trying to use your JQuery-vertical-accordion plugin menu system but in the project I´m working on I don´t know from where the user is coming.
    My question is: is it posible to have a special class (maybe something like “active”) on a submenu item so the menu branch to which it belongs is expanded when the uservisit the page for the first time ?

    Thank you in advance
    Rober

    • Hi Rober – actually I just modified the plugin yesterday to do exactly that so it can handle similar requirements for the WordPress plugin version. I havent had chance yet to update the jQuery download though.

      You can get version 2.5 from the following URL – http://www.designchemical.com/lab/jquery-plugins/jquery-vertical-accordion-menu/js/jquery.dcjqaccordion.2.5.js

      There are 2 new options in this version:

      classExpand – the class given to the sub-menu parents to identify which ones to open
      autoExpand – if true the sub-menus with parent that have ‘classExpand’ will be set open on page load

      Hope this is what you were wanting?

    • One other note for the new version – in order for autoExpand to work the saveState option must also be set to true

  • Hi, this is very nice but I’m using it in a CMS environment. Is it possible for the sub menu items to drop down on HOVER, not by clicking the top level item?

    Thanks,

  • Great menu.. I am using it with Semiologic theme and I have a gap between each Menu item, while I really want no gap as shown on your demo page here:
    http://www.designchemical.com/lab/demo-wordpress-vertical-accordion-menu-plugin/

    Do you know of a fix for this..

    Thank you

    Alan

    • Hi Alan,

      I havent seen the semiologic theme but if there is a gap with one of the plugin skins it sounds like there may be margins set in the theme for widget links. If you can send me a link to the page I can take a look

  • Thanks a ton. This is some really great stuff.

  • Hi. I mean when the sub-menu is clicked.

    I’m able to give the sub-items their own look through css, but the script doesn’t allow the sub-item it’s own active state.

    Thanks for replying.

    • Hi Roy,

      You can modify the jQuery as follows:

      $(document).ready(function () {
        $('#nav li a').click(function(){
      	if($(this).next().length){
      		if ($(this).attr('class') != 'active'){
      			$('#nav li ul').slideUp();
      			$(this).next().slideToggle();
      		}
      	}
      	$('#nav li a').removeClass('active');
      	$(this).addClass('active');
        });
      });
      

      This will then add the class “active” to any link clicked but only open/close those that have sub menus – see demo:

      http://www.designchemical.com/lab/jquery/demo/jquery_simple_accordion_menu_3.htm

  • What a beautiful, light, efficient menu.

    Is it possible to ALSO give a “sub-item” it’s own active appearance without interfering with the “item’s” state?

    • Hi Roy,

      Thank you. Do you mean when the sub-item is clicked or just when the sub-menu is open?

  • I don’t have a link just yet. I have been doing testing through a local folder on my hd. Would a screen shot of my source code work? You can email me if that would help any

  • Thanks! I think I’m getting there. I am having a small issue now that I have the plugin and the call function code in place. When the page opens up, “nav” is fine but “nav-2″ is open and when clicked won’t close – closes and reopens. With the “nav” section when clicked to open for the first time will open but when clicked again to close will close and reopen – won’t stay closed :/ I’m still trying to learn as much as I can in the varying jquery codes but it’s taking some time. Anyways the original code of yours that I was using was the following:

    $(‘#nav > li > a’).click(function(){
    $(‘#nav li ul’).slideUp();
    if ($(this).next().is(“:visible”)){
    $(this).next().slideUp();
    } else {
    $(this).next().slideToggle();
    }
    $(‘#nav li a’).removeClass(‘active’);
    $(this).addClass(‘active’);
    });

    Would the plugins have to be under the same tag?? Appreciate all the help.

    • Hi Adam,

      Do you have a link I could look at?

  • excuse my newbie-ness to the jquery language but i am confused on changing the selector so that i may add a second menu to the same page. can you show an example? or show what needs to be changed out?? first menu works great, now i would love to get a second on the same page. thanks!

    • Hi Adam,

      The best way is to turn the code into a plugin, which you can then use multiple times.

      Below is the plugin version of the code:

      jQuery.fn.accordionMenu = function(){
          return $(this).each(function(options){
              var $accordionMenuItem = this;
              var accordionLink = $('> li > a',this);
              $(accordionLink).click(function(){
                  if ($(this).attr('class') != 'active'){
                      $('li ul',$accordionMenuItem).slideUp();
                      $(this).next().slideToggle();
                      $('li a',$accordionMenuItem).removeClass('active');
                      $(this).addClass('active');
                  }
              });
          });
      };
      

      To use the plugin you would then call the function using the following code:

      $(document).ready(function () {
          $('#nav, #nav-2').accordionMenu();
      });
      

      In the above example we have 2 different accordion menus – nav and nav-2

      I have set up a demo page using the above code – Simple Accordion Menu jQuery Plugin

  • I haven’t a website yet. But here is my code. I can’t use the cookie plugin because it interferes with extjs. However, I made a function to get the cookie.
    Here is my code:

    $(document).ready(function () {
    var checkCookie = getCookie(“nav-item”);
    if (checkCookie != “”) {
    $(‘#nav > li > a:eq(‘+checkCookie+’)').addClass(‘active’).next().show();
    }
    $(‘#nav > li > a’).click(function(){
    var navIndex = $(‘#nav > li > a’).index(this);
    document.cookie = “nav-item=”+navIndex;
    if ($(this).attr(‘class’) != ‘active’){
    $(‘#nav li ul’).slideUp();
    $(this).next().slideToggle();
    }
    });
    $(‘#nav li a’).click(function(){
    $(‘#nav li a’).removeClass(‘active’);
    $(this).addClass(‘active’);
    });

    });

    function getCookie ( cookie_name ){
    var results = document.cookie.match ( ‘(^|;) ?’ + cookie_name + ‘=([^;]*)(;|$)’ );
    if ( results )
    return ( unescape ( results[2] ) );
    else
    return null;
    }

  • Hi!
    I solved my problem by reading through this thread once more. It was very simple: I changed the event click to hover in the original jquery code, the meny stays open and “jumps” less.

  • hi,
    First, thank you very much for your menu. I use it with the cookie and the active submenus. However, when I refresh the page I have the problem, that the submenu is not active anymore. Could you fix this Problem because I am very new to jQuery and I can’t do it myself.
    Thank you very much.

    • Check that you have the jQuery cookie plugin loaded. If you can post the link to the page I will take a look

  • Thank you for sharing Horizontal Accordion code!
    Very useful.

  • Is it possible to have 2 Vertical Accordion Menus on one page?

    • hi,

      This shouldnt be a problem. Just create another copy of the jQuery code with a different selector. I have actually turned the code into a jQuery plugin, which is used on the WordPress plugin version. I will add a blog post soon with the details

  • I’ve done it! Thanks however!

    $(document).ready(function(){
    $(‘#nav > li’).click(
    function(){
    if ($(‘> a’,this).attr(‘class’) != ‘active’){
    $(‘#nav li ul’).slideUp();
    $(‘a’,this).next().slideToggle();
    $(‘#nav li a’).removeClass(‘active’);
    $(‘> a’,this).addClass(‘active’);
    } else {

    $(‘#nav li ul’).slideUp();
    $(‘#nav li a’).removeClass(‘active’);
    }
    });
    });

  • Hi,
    I would like something like Jeffrey posted in Dec 14th 2010 but always using click and not hover…How could I do this please?
    thanks!

  • I don’t know if this tread still is active, but i’ll try:

    Very nice and easy to follow tutorial, but when you are not a java script programmer (I am not) you are stuck if you want to make the simplest changes in the code. I have adjusted the code to fit in the auto nav function in the CMS Concrete5, but the hover makes the menu jump in some (it’s) understandable) cases.
    Try this demo:
    http://vevstova2.no/index.php/no/home

    Maybe turning of the auto close function will stop the jumping, but I don’t have the knowledge to do it unfortunately.
    Very happy to get hints! :-)
    audun

  • Hi, I am looking a nice accordin menu in jquery ( I don’t know anything about Jquery) I need a menu that keeps the menu open on active page, and that can be fully closed. I like this menu, but don’t found out where I could download it, if it is not possible, can anyone send me a link to a working menu.

    Thank to everyone.

    Gwen

    • Hi,

      The cookie is being set multiple times. In order to overcome this the path for the cookie also needs to be set using – { path: ‘/’ }. So the the cookie code becomes:

      $.cookie("nav-item", navIndex, { path: '/' });
      
  • Seemed to work, however on putting it live, the first submenu stays open, even when clicking on other submenu-items.

    • Can you post a link and I will take a look

  • spoke too soon: need jquery.cookie.js of course

  • Ok, testing this (using WordPress and $j voor jQuery (noConflict) gives

    $j.cookie is not a function

    var checkCookie = $j.cookie(“nav-item”);

  • Great stuff! One problem: on selecting a parent menu-item the submenu slides out (as expected), but closes when the page loads.

  • is it possible to see the demo (mouseover + cookie with open/close icons)?

  • thanks, very useful ;)

    I will use the mouseover + cookie and add icons (open/close) is it possible?

    • Yes. Can use the above code for the hover and apply the cookie code from the previous example. The icons are obviously handled using CSS

  • Thank you very much… ! Seriously, you’re great.

  • I’m using this menu. I don’t use onclick but hover. That works, but I have a question:

    How can I let the menu go back to its orginal when i’m not hovering an item?

    Hoping you understand my question.

    • Hi,

      You can use the following code to handle both hover and lose focus:

      $(document).ready(function(){
        $('#nav > li').hover(
      	function(){
      		if ($('> a',this).attr('class') != 'active'){
      			$('#nav li ul').slideUp();
      			$('a',this).next().slideToggle();
      			$('#nav li a').removeClass('active');
      			$('> a',this).addClass('active');
      		}
      	},
      	function(){
      			$('#nav li ul').slideUp();
      			$('#nav li a').removeClass('active');
      	});
      });
      

      Instead of selecting the anchor tag tag I have changed it to the list tag so that the hover event also stays active for the sub-menus. See demo

  • good stuff. quick question. I’ve got everything working, including using cookies to remember which item is open. My only issue is that I cannot seem to keep the open item “active” when I go to another page. So, it remembers which to open to, but the header item that is open does NOT show active style any longer.

    any thoughts on how I might maintain the active style from page to page?

    • Hi,

      Sorry forgot to add that! For the line that checks the cookie change the following:

      FROM:

      if (checkCookie != “”) {
      $(‘#nav > li > a:eq(‘+checkCookie+’)').next().show();
      }

      TO:

      if (checkCookie != “”) {
      $(‘#nav > li > a:eq(‘+checkCookie+’)').addClass(‘active’).next().show();
      }

      I have updated the demo

  • when i click a submenu item it should be active. how can i do this? pls help me. see this
    http://i51.tinypic.com/2eczrcx.jpg

    • Hi,

      You can change the jQuery as follows:

      $(document).ready(function () {
         $('#nav > li > a').click(function(){
           if ($(this).attr('class') != 'active'){
             $('#nav li ul').slideUp();
      	   $(this).next().slideToggle();
      	 }
        });
          $('#nav li a').click(function(){
      	   $('#nav li a').removeClass('active');
      	   $(this).addClass('active');
      	});
      });
      

      This will now also add class “active” to the sub-links

  • Similar to phil’s question. What if you want the navigation to be open on a page that’s that the 1st link/Home page? Is that possible?
    Thanks!

    • Hi,

      See reply to Phil’s question – you can add a couple of lines of jQuery to open the first link

  • [...] the jQuery code from one of our previous tutorials on creating a simple vertical navigation menu we can add the very useful jQuery cookie plugin to create a more advanced navigation menu that [...]

  • this is works fine in firefox but not in the IE 6 and above. so please guide how to fix it.

    Thanks in advance. very urgent… I have to finish is project by this weekend..

    • Hi,

      Works fine in IE7. Unfortunately I dont support IE6 so you need to try and sort that one out yourself.

  • Cool menu!!
    I have one question. How i can use this menu with jquery.cookie.js?

  • Thanks!

  • My client wants a HOME menu item, so when I arrive, that menu item needs to be selected, how do I do this?

    • Hi Phil,

      Assuming that “Home” is the first menu item you can add the following to the jQuery code:

      $('#nav li:first ul').show();
      $('#nav li:first a').addClass('active');
      

      So the complete code would be:

      $(document).ready(function () {
        $('#nav &gt; li &gt; a').click(function(){
           if ($(this).attr('class') != 'active'){
             $('#nav li ul').slideUp();
      	   $(this).next().slideToggle();
      	   $('#nav li a').removeClass('active');
      	   $(this).addClass('active');
      	 }
        });
        $('#nav li:first ul').show();
        $('#nav li:first a').addClass('active');
      });
      
  • Can u make the accordian horizontal?

  • Nice tutorial. It should also be nice to be abel to close the menu again.

    • Thanks.

      If you change the jQuery code to the following it will allow the menu to close:

      $('#nav > li > a').click(function(){
            $('#nav li ul').slideUp();
      	   if ($(this).next().is(":visible")){
      		   $(this).next().slideUp();
      	   } else {
      	   $(this).next().slideToggle();
      	   }
      	   $('#nav li a').removeClass('active');
      	   $(this).addClass('active');
        });
      

      See demo here.