开发者

How to remember last state with Jquery?

开发者 https://www.devze.com 2022-12-24 02:46 出处:网络
I have a menu with submenus that can be toggled (hide/show type deal). Is there a relatively easy way to remember last state of the menu?

I have a menu with submenus that can be toggled (hide/show type deal). Is there a relatively easy way to remember last state of the menu? (I hide/show submenu when clicking on a header and change a style of the header so the background arrow will change (up/down)). It works fine, but I'd like it to remember last state, so when user goes to another page on the site and gets back, the menu shows the same way as user left it. I'm not really good with cookies so any help will be appreciated. Yeah, menu is generated dynamically from the db using PHP. There are now only 2 headers with submenus, but there will be more so I'd need some method that's "scalable" for any number of submenus. There is also no need to remember it for longer then one visit.

Current url is开发者_如何学Python this: http://valleyofgeysers.com/geysers.php


You can use the jQuery cookie plugin for this

Just set the cookie when hiding, showing, then on load set what's shown based on any cookies set. You can do this by naming the cookies like this: "display" - this.id

If you wrapped each menu with a <div id="unique"> like you have with geysers (so we have a unique ID to set a cookie for), something like this should work:

$('h3').next('.g_menu').filter(function() {
  return $.cookie("expanded-" + $(this).parent("[id]").attr("id"));
}).hide();

$('h3').click(function(){
  $(this).toggleClass('closeit').toggleClass('openit');
  var menu = $(this).next('.g_menu');
    if(menu.is(':visible')) {
        menu.fadeOut(50);
        $.cookie("expanded-" + $(this).parent().attr("id"), true);
    } else {
        menu.fadeIn(980);            
        $.cookie("expanded-" + $(this).parent().attr("id"), null);
    }
});​

To make this work, wrap <h3 class="openit">Other</h3><div class="g_menu"></div> in a <div id="other"></div> You can play with a sample to see this in action here.

0

精彩评论

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