How to remember the last state with jQuery?

I have a menu with a submenu that can be switched (hide / show transaction type). Is there a relatively easy way to remember the last state of the menu? (I hide / show the submenu when I click on the title and change the style of the title so that the background arrow changes (up / down)). It works fine, but I would like it to remember the last state, so when the user goes to another page on the site and returns, the menu is displayed just like the user. I am not very good at cookies, so any help would be appreciated. Yes, the menu is dynamically generated from db using PHP. Now there are only 2 headers with submenus, but there will be more, so I need some method that "scales" for any number of submenus. There is also no need to remember this longer than once.

Current URL: http://valleyofgeysers.com/geysers.php

+1
source share
1 answer

You can use jQuery cookie for this.

Just set a cookie on hiding, showing, and then on loading, set what is shown based on any cookies. You can do this by naming cookies as follows:"display" - this.id

If you wrapped each menu using <div id="unique">, like you do with geysers (so we have a unique identifier for setting cookies), 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 do this work, wrap <h3 class="openit">Other</h3><div class="g_menu"></div>in. <div id="other"></div> You can play with the sample to see it in action here .

+4
source

Source: https://habr.com/ru/post/1741828/


All Articles