Search code examples
jquerycookiesslidedownjquery-cookie

How to set jQuery Cookie for slideDown menu?


I have a slideDown menu and I want to remember the last state of the menu so that on page load the last state is already selected. I am trying to accomplish this by using jQuery.cookie and this is what i did:

$("#menu h3").click(function(){
    $("#menu ul ul").slideUp();
    if(!$(this).next().is(":visible")){
        var id = $(this).attr('id');   
        $.cookie(id, $(this).is(':visible') ? "closed" : "open");
        if ($.cookie(id) == "open") {
            $(this).next().slideDown();
        }
    }
});

>> jsFiddle <<
When I reload the page I don't get the last state and .slideDown() doesn't work. Can anyone help me?

Thanks!


Solution

  • I modified your code a little. Try this:

    var active = $.cookie('active'),
        $h3 = $("#menu h3"),
        $activeH3 = $h3.filter('#' + active);
    
    $h3.click(function(e, speed) {
        $("#menu ul ul").slideUp(speed);
        if (!$(this).next().is(":visible")) {
            $(this).next().slideDown(speed);
            $.cookie('active', this.id);
        }
    });
    
    if ($activeH3.next().is(':hidden')) {
        $activeH3.trigger('click', [0]);
    }
    

    Make sure you also set ids for your h3 elements.

    Demo http://jsfiddle.net/K4pUV/1/