Question

I've got a page with a list of countries and a sublist of it's cities. For the sake of simplicity I made a http://jsfiddle.net/PPexP/7/ with just a few menus and a submenus

A short preview of the javascript and the jquery.cookie link: https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js

$(document).ready(function(){
function checkCookie() {
    if($.cookie('mainlevel')) {
        var array = [];
        array.push($.cookie('mainlevel'));
        console.log(dirArray)
    }
} 

$('.mainitem').click(function() {    
    var $cookie = ($(this).text());
    console.log($cookie)
    $cookie = $cookie.split(',');
    $(this).next('ul').toggle(function() {
        console.log('fired');
        var CookieSet = $.cookie('mainlevel', [$cookie], { expires: 30 });
    });
});

});

The HTML is generated and is like in the JSFIDDLE, i cant change the html is.

What is supposed to happen:

  1. When clicked on a mainmenu item, submenu pops out and a cookie is set so next time menu is still open. It checks the name of the mainmenu and that will be the cookie

JSfiddle doesn't seem to load jQuery cookie plugin, but what i am trying is, to set the name of main menu after a click in an array. when the page loads, it checks the cookie, if there is, in the array will be the mainmenu items that should be expanded on load.

Was it helpful?

Solution

I've modified your code. See inline comments. See the entire code here and the LIVE DEMO.

$('.subitems').hide();

// check cookie
checkCookie();

function checkCookie() {
    // the cookie exists
    if($.cookie('mainlevel')) {
        var index = $.cookie('mainlevel');
        $(".mainitem:eq(" + index + ")").find("ul").show();
    }
}

// click on .mainitem
$('.mainitem').click(function() {
    // get the index
    var cookie = $(this).index();

    // hide all subitems
    $(".mainitem").find("ul").slideUp();

    // toggle the ul that is in the clicked item
    $(this).find('ul').toggle(function() {
        // save the cookie
        $.cookie('mainlevel', [cookie], { expires: 30 });
    });

    // toggle if change happend :: thanks @lolotron
    if (previousValue != cookie) {            
        $(".mainitem").find("ul").slideUp();        
        $(this).find('ul').slideDown();
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top