Searle Searle - 2 years ago 59
HTML Question

Keep list toggle state on page refresh

I'm having trouble making it so that when a logged in user hides a certain part of the menu for it to stay that way during their session.

$(document).ready(function () {
$('h1.tree-toggler').click(function () {
$(this).parent().children('ul.tree').toggle(300);
});
});


With this HTML:

<div>
<h1 class="tree-toggler">Heading</h1>
<ul class="tree">
<a href="#"><li>Link 1</li></a>
<a href="#"><li>Link 2</li></a>
<a href="#"><li>Link 3</li></a>
<a href="#"><li>Link 4</li></a>
<a href="#"><li>Link 5</li></a>
</ul>
</div>


The toggle works perfectly, but it doesn't stay like it when you change page.

How can I make it stay how it is toggled on the next page?

Answer Source

You can follow the link: How to get JS variable to retain value after page refresh?

You can also use the following code for your purpose:

$(document).ready(function () {
    if(localStorage.getItem("toggleState") == "1")
    $('ul.tree').hide();

  $('h1.tree-toggler').click(function () {
    var ts = localStorage.getItem("toggleState");
    if(ts == null || ts == "0") {
            var tv = "1";
            localStorage.setItem("toggleState", tv);
        }else {
        var tv = "0";
            localStorage.setItem("toggleState", tv);
    }
    $(this).parent().children('ul.tree').toggle(300);
  });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download