I am trying to build an array of objects to save a menu's state in a cookie but it is not updating because it is not finding the proper index containing the object I need to update visibility for. What am I doing wrong and/or can you point me in the right direction?
$(document).ready(function() {
var menu = new Array();
$("#vertical-nav .head").click(function() {
var c = $(this).next().attr('name');
$(this).next().slideToggle("slow", function() {
if ( $(this).next().is(':visible') ) {
menu.push({
name: c,
visible: true,
});
} else {
var index = $.inArray(c, menu);
console.log("INDEX: " + index);
menu[index] = { name: c, visible:false };
}
});
console.log(menu);
});
});
This is what I ended up with:
$(document).ready(function() {
var menu = new Array();
if ( $.cookie('menu') ) {
var items = JSON.parse($.cookie('menu'));
for ( var item in items ) {
if ( items[item].visible ) {
$("div[name='" + items[item].name + "']").show();
}
menu.push(items[item]);
}
}
$("#vertical-nav .head").click(function() {
var c = $(this).next().attr('name');
if ( $(this).next().is(":visible") ) {
hide(this, c);
} else {
show(this, c);
}
});
function show(obj, c) {
$(obj).next().slideDown('slow', function() {
var elementExists = false;
if ( menu.length > 0 ) {
for ( var item in menu ) {
if ( menu[item].name == c ) {
elementExists = true;
menu[item].visible = true;
}
}
}
if ( !elementExists ) {
menu.push({
name: c,
visible: true,
});
}
$.cookie('menu', JSON.stringify(menu));
});
}
function hide(obj, c) {
$(obj).next().slideUp('slow', function() {
if ( menu.length > 0 ) {
for ( var item in menu ) {
if ( menu[item].name == c ) {
menu[item].visible = false;
}
}
}
$.cookie('menu', JSON.stringify(menu));
});
}
});
console.log(menu)at the end is happening before your if statement that modifiesmenu. Stick it inside a setTimeout with a 5 second delay and you'll see what i mean.