Themeforest

jQuery Simple Vertical Accordion Menu with Cookies

Using 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 remembers your visitors last location.

The HTML, jQuery and CSS

To speed up the tutorial we will assume that you have already followed the initial postings and therefore understand how to create the basic HTML/CSS structure for a vertical accordion menu and that you have the preliminary jQuery in place.

Using jQuery Cookies

What jQuery cookies allows us to do is very easily create/modify/store a cookie on the visitors computer that will hold the position of the last menu item visited. When they next visit the site we can therefore use this value to automatically open the relevent menu section.

Creating a jQuery Cookie

To create a cookie we simply declare the cookie name, followed by the value. For our accordion menu we will therefore create a cookie named “nav-item” and its value will be the index value of the last anchor tag clicked. So to create this we use:

$('#nav > li > a').click(function(){
      var navIndex = $('#nav > li > a').index(this);
	  $.cookie("nav-item", navIndex);
	  $('#nav li ul').slideUp();
	   if ($(this).next().is(":visible")){
		   $(this).next().slideUp();
	   } else {
	   $(this).next().slideToggle();
	   }
	   $('#nav li a').removeClass('active');
	   $(this).addClass('active');
  });

In the above code – line 2 gets the index value and line 3 sets the cookie.

Using the Cookie Value

Now that we have a cookie on their computer we need to add the jQuery code that will check the visitors browser when the page loads, retrieve the cookie if it exists and use this to open the appropriate menu section:

var checkCookie = $.cookie("nav-item");
  if (checkCookie != "") {
	$('#nav > li > a:eq('+checkCookie+')').next().show();
  }

That is basically all that is required. Put it all together and the complete code …

The Complete jQuery

$(document).ready(function () {
  var checkCookie = $.cookie("nav-item");
  if (checkCookie != "") {
	$('#nav > li > a:eq('+checkCookie+')').next().show();
  }
  $('#nav > li > a').click(function(){
      var navIndex = $('#nav > li > a').index(this);
	  $.cookie("nav-item", navIndex);
	  $('#nav li ul').slideUp();
	   if ($(this).next().is(":visible")){
		   $(this).next().slideUp();
	   } else {
	   $(this).next().slideToggle();
	   }
	   $('#nav li a').removeClass('active');
	   $(this).addClass('active');
  });
});

Check out the online 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.

33 Comments

  • Lee,

    Ignore my last question…if you don’t load all js…it will never work!
    It works now.

    Onno

  • Lee,

    Nice plugin, but for me it is comming with a small issue. I can run it without cookies, no problem, but as soon as I try to use cookies, it all fails and no menu will open. If i debug, i find the feedback that $.cookie is not a function???
    If I run the demo it works. I am a bit puzzled, can you help?

    Onno

    • Hi,

      Sounds like the jquery cookie plugin is not being loaded. This may be due to your hosting

  • Hi!

    Works great until I give the children children.

    A. Level 1
    B. Child 1
    B. Child 2
    C. Child2-Child1
    C. Child2-Child2
    B. Child 3
    B. Child 4
    C. Child4-Child1
    C. Child4-Child2

    see where I’m going here? how do you handle this? I tried using the plugin, I get nothing. no movement at all. please advise. I am very confused…

    thanks!

    • Hi,

      The plugin should work OK. If you are not getting any accordion effects it sounds like there is an error with the jquery

      • yeah, but how do i find that? i am very much as ‘-use-as-is-type’ query person. when it comes to customization, it need hand holding.

        thanks!

        l;o)

        • Check the site using firebug. This will tell you where any errors are occuring

  • How to reset the Cookie?

    I’d like to reset it, by loggin out. Have no clue of JS.. -.-’

    Greez

    • You can reset the cookie just by passing it an empty value

      • Thanks for your fast reply :)

        Well, that’s what I tried, but I really don’t know how to do anything in Java :$

        I tried:

        var checkCookie = "";

        Probably far far away of the correct solution.

  • Hi, This Worked Gr8! but how to highlight li link after click ?? ( with other color or background)
    Ex:
    Menu I
    1
    2
    3
    4
    Menu II
    1
    and more

    after click in 1, save in cookie and highlight in current and any page,

    Thanks Best regrads

    • Hi,

      The active menu item is given the CSS class “active” so you can style the link in your CSS style sheet using #nav li a.active {}

      • HI, Thanks For Reply But I test and try this, not worked !!

  • hi – thanks for the script – I have downloaded “Jquery vertical accordion menu plugin”.

    I am tearing my hair out over one problem – I hope you can help. It is cookie related I think.

    I set up my accordion menu and to test it have 3 HTML pages – 1. the Home page (index.html) and under link named “Apricot Kernels” I have two more pages – 2. “Why eat apricot kernels?” (apricot1.html) and 3. “For those without cancer” (apricot2.html).

    THe problem is that when you click on a sub-menu link it loads the page but the sub-menu closes again. I need it to stay open. HEEEELP!!

  • Hello. This script rules. But can you make it for the submenu too? Is it’s possible? the menu open and the one clicked to be highlighted with other color?

    • Hi Rogerio – if you check out our accordion menu plugin for jquery it should be able to handle all your requirements:

      Vertical Accordion Menu Plugin

  • Looks like it’ll work great, I see now that the cookie name was not being set before. Thank you again, this is shaping up to be my favorite accordion plugin available.

    • ok great. if you have any further recommendations for features, etc, let me know

  • Thank you sir! I will test it out when I get a moment.

  • I setup this simple test: http://www.zirgo.com/test.php

    I used the code from your examples. Clearly I must be doing something wrong?

  • Thanks for the speedy reply, if I can’t get it to work, I’ll put something out on an external server.

    • Only thing I can think of is that it sets the cookie based on the parent ID – if this isnt set then the cookie may not work … I need to maybe review that method!

  • Hm, that’s what I thought, but the cookie isn’t even being generated. I’ll see if I can get it to work outside my web app.

    • It may not be generated on your local server. If you have problems with it externally let me know and I will take a look

  • Greetings, I have just installed your plugin for the first time (internal test server) and it works great! However, do you have a tutorial on how to use the cookie state option? I have enabled the flag in the plugin (saveState: true) and have included the jquery.cookie.js above the accordian plugin, but am not sure where to go from here.

    • Shane – That’s all you need to do actually if using the jquery accordion menu plugin. The plugin automatically generates the cookie name based on the accordion menu element so there is nothing to set.

  • [...] This post was mentioned on Twitter by Pinceladas da Web, Marcelo Ceribelli, Lucas Max, Rodrigo Tormente , Guilherme Mateus and others. Guilherme Mateus said: Muito massa! o/ RT: @pinceladasdaweb: jQuery Simple Vertical Accordion Menu with Cookies: http://migre.me/3Ro1d [...]

  • Thank you.
    Have you ever had idea to pack it as a WP plugin for use with WP 3.0 menus. No competition as far as I know.

Leave a comment

To add code to your comments wrap the code text in [text][/text] tags