开发者

Setting cookies for a collapsable jQuery menu when using .toggle()

I'm trying to set up coo开发者_开发百科kies 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/

$('.menu-sidebar li:has(ul) a').click(function() {
    $(this).next().toggle();
    if ($(this).next().is(':visible')) {
        $.cookie($(this).text(), 'expanded');
    }

    if ($(this).next().is(':hidden')) {
        $.cookie($(this).text(), 'collapsed');
    }
});

$('.menu-sidebar > li').each(function() {
    var verticalNav = $.cookie( $(this).children('a').text() );
    if (verticalNav == 'expanded') {
        $(this).find('ul').show();
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜