11

I have this HTML toggle button for my menu:

<a href="#" id="toggle_nav" class="sidebar-toggle" data-toggle="offcanvas" role="button">

How can i save the toggle state to reload it on page load

I have started off with:

$(document).ready(function() {
    $("#toggle_nav").toggle(function() {

    });
});

but im not sure what to use to keep the state

charlie
  • 415
  • 4
  • 35
  • 83

6 Answers6

6

Like people are saying in the commends you can use html 5 web storage.

You have 2 types:
- localStorage - stores data with no expiration date
- sessionStorage - stores data for one session

how to set:
localStorage.setItem("name", "value");

How to get the value
localStorage.getItem("name");

So now can you do a simple check like:

if (localStorage.getItem("toggle") === null) {
    //hide or show menu by default
    //do not forget to set a htlm5 cookie
}else{
   if(localStorage.getItem("toggle") == "yes"){
     //code when menu is visible
   }else{
     //code when menu is hidden
   }
}

More information here

Vinc199789
  • 1,046
  • 1
  • 10
  • 31
  • if there is no value set at all how do i know if the menu state is hide or show ? – charlie Jul 20 '15 at 20:12
  • No. You can check if a storage with the specific name exists. When you visit the site for the first time the storage is not set ofcourse. what you can do is check if there is a cookie with that name and if not hide or show the menu like you want. – Vinc199789 Jul 20 '15 at 20:17
  • I change the code so that it will check if there is a cookie set and if not than can you hide or show the menu like you want – Vinc199789 Jul 20 '15 at 20:19
  • @Vinc199789 a little bit off-topic, do you have any idea how can I implement this in my situation? http://stackoverflow.com/questions/32687806/how-to-keep-the-menu-state-on-page-reload – typo_ Sep 25 '15 at 08:31
  • 1
    @typo_78 you have to use localstorage for this (like my example code in my answer). First set a localstorage value when the users pressed the link for the first time. In the code part where I check the value of the localstorage you have to say what should happen when the value is true or false. – Vinc199789 Sep 26 '15 at 07:27
  • thank you @Vinc199789, meanwhile I solved this using jQuery-Storage-API and `storage=jQuery.sessionStorage;` the first step is done, now it comes the hard part :) http://stackoverflow.com/questions/32770490/how-to-keep-elements-non-refreshed – typo_ Sep 26 '15 at 07:31
  • @typo_78 I never work with ajax so I can't help you with the ajax problem. Just make sure that everything is loaded well and look at what rules the error started and look if you made a typing mistake or something – Vinc199789 Sep 26 '15 at 07:36
  • @Vinv199789 I am keep checking and searching something is wrong for sure. thank you for your interest. regards, – typo_ Sep 26 '15 at 07:38
1

Use a hidden field. Use JS to set this hidden field value whenever the panel is opened or closed, and to check the hidden field on pageload. Example-

In your JS, I use one function to set which panels are open/closed and a 2nd to arrange them. This example is based on having multiple panels on your page but you can quickly change it to handle just one panel if needed.

function init() {
    if ($("#hdnOpenPanels").val()) {
        $(".fixPanels").click();
    }
}
// Ensures that the correct panels are open on postback
$(".checkPanels").click(function () {
    var checkPanel1= $("#Panel1").hasClass("in");
    var checkPanel2 = $("#Panel2").hasClass("in");
    var checkPanel3 = $("#Panel3").hasClass("in");

    $("#hdnOpenPanels").val(checkPanel1 + "|" + checkPanel2 + "|" + checkPanel3);
});

$(".fixPanels").click(function () {
    if ($("#hdnOpenPanels").val().split('|')[0] === "true") {
        $("#Panel1").collapse('show');
    } else {
        $("#Panel1").collapse('hide');
    }

    if ($("#hdnOpenPanels").val().split('|')[1] === "true") {
        $("#Panel2").collapse('show');
    } else {
        $("#Panel2").collapse('hide');
    }

    if ($("#hdnOpenPanels").val().split('|')[2] === "true") {
        $("#Panel3").collapse('show');
    } else {
        $("#Panel3").collapse('hide');
    }
});

Now you have two easy classes available to add to any items that will require the page to know which panels are open (.checkPanels) and also to "fix" which panels should be open (.fixPanels). If you have modals on the page they'll need to "fixPanels" when they closed (even though there may not have been a postback).

On your code-behind:

Add this to your PageLoad:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["sPanels"] != null)
        {
            hdnOpenPanels.Value = Session["sPanels"].ToString();
            Session.Remove("sPanels");
        }

        if (IsPostBack){...}
        else {...}
    }

Finally, on any code-behind functions that will be causing a post-back affecting the panels, add this line at the bottom of the function(s):

Session["sPanels"] = hdnOpenPanels.Value;
Haensz
  • 127
  • 5
0

There are any number of ways to accomplish this, including local storage, cookies, URL parameters, anchor fragments, and server-side storage.

If you need to persist the value for a user, regardless of browser, you'll need to store it on the server side as a user preference against an identified user's profile.

If you need to persist against a single browser instance, regardless of user, you can use a client-side solution like localStorage (for persistence across browser sessions) sessionStorage (for persistence within a single browser session) or cookies (which can be configured to do either).

For example, here is a solution that uses localStorage to persist the state of a toggle across page reloads and browser sessions.

This code does not run in an SO snippet, so see this Fiddle for a demo.

Javascript

var menuStateKey = "menu.toggle_nav.state";
$(document).ready(function() {
    var $nav = $("nav");

    var setInitialMenuState = function() {
        // Note: This retrieves a String, not a Boolean.
        var state = localStorage.getItem(menuStateKey) === 'true';
        setNavDisplayState(state);
    };

    var toggleNav = function() {
        var state = $nav.is(':visible');
        state = !state;
        localStorage.setItem(menuStateKey, state);
        setNavDisplayState(state);
    };

    var setNavDisplayState = function(state) {
        if (state) {
            $nav.show();
        } else {
            $nav.hide();
        }
    };

    $("#toggle_nav").click(toggleNav);

    setInitialMenuState();
});

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>I am the nav</nav>
<a href="#" id="toggle_nav" class="sidebar-toggle" data-toggle="offcanvas" role="button">Toggle</a>
Palpatim
  • 9,074
  • 35
  • 43
0

You can store toggle state in localStorage object.

// Check browser support
if (typeof(Storage) != "undefined") {
    // Store
    localStorage.setItem("toggleState", value);
    // Retrieve
    localStorage.getItem("toggleState");
} else {
    "Sorry, your browser does not support Web Storage...";
}

Check out Local Storage - Dive Into HTML5

There are JQuery plugins available to facilitate this.

$.localStorage;
storage=$.localStorage;
storage.set('foo','value');
storage.get('foo');

Read more at Jquery Storage API.

Cheers !

RevanthKrishnaKumar V.
  • 1,855
  • 1
  • 21
  • 34
Sachin Thapa
  • 3,559
  • 4
  • 24
  • 42
0

As others explained we can use localStorage(HTML5) or else we can use cookies

Please refer this article on how to persist the data using cookies.

As this implementation requires less data to be stored in cookie. Using cookie would be the good approach for your implementation.

RevanthKrishnaKumar V.
  • 1,855
  • 1
  • 21
  • 34
Varun
  • 597
  • 7
  • 26
0

You can extent toggle

$.prototype._toggle = $.prototype.toggle;
$.prototype.toggle = function() { 
// save to localStorage
$.prototype._toggle.call(this) 
}

And write code that use localStorage to start toggle

tkeram
  • 214
  • 1
  • 5