I’m trying to set up cookies on a collapsable vertical list, I’m using .toggle() to hide and show the list and jQuery Cookie Plugin. I have really simple nav like this:
<ul class="menu-sidebar">
<li>Item 1</li>
<li><a href="#">Item 2</a>
<ul>
<li>Item 2.1</li>
</ul>
</li>
<li><a href="#">Item 3</a>
<ul>
<li>Item 3.1</li>
</ul>
</li>
<li>Item 4</li>
</ul>
With following CSS:
.js .menu-sidebar li ul{display:none;}
Then I toggle the list like this:
jQuery(document).ready(function(){
$('.menu-sidebar li:has(ul) a').click(function(){
$(this).next().toggle();
});
});
It’s simple and works great but I can’t really wrap my head around how to se cookies on that. I’ve been trying to do it like this:
$('.menu-sidebar li:has(ul) a').click(function(){
$(this).next().toggle();
if ($(this).next().is(':visible')){
$.cookie('verticalNav', 'expanded');
}
if ($(this).next().is(':hidden')){
$.cookie('verticalNav', 'collapsed');
}
var verticalNav = $.cookie('verticalNav');
if (verticalNav == 'expanded'){
$(this).next().show();
}
});
With no luck. Any tips? Thanks! 🙂
Take that last block out of the click() method. It’s redundant inside of it. (And, of course, wrap it all inside a
$(document).ready(function() {...});block.)UPDATE: This code will work with multiple submenus by assigning a different cookie value to each one. http://jsfiddle.net/GDudf/13/