keep toggle state of menu using JQuery

北城以北 提交于 2021-02-02 08:11:33

问题


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


回答1:


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




回答2:


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;



回答3:


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>



回答4:


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




回答5:


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 !




回答6:


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.



来源:https://stackoverflow.com/questions/31099361/keep-toggle-state-of-menu-using-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!