简体   繁体   中英

Remembering the toggle state via cookie

I was looking for a way to remember the toggle state and came across js-cookie on github. The document explains how to create, read and delete a cookie. I was hoping for an example which could have helped me understand a lot better.

I need to toggle a form to show all fields or only the mandatory ones (form is a bit huge, but all fields aren't necessary, so thought of hiding ones which aren't and if the user somehow wish to furnish all detail can simply toggle to show all fields).

This toggle example is fairly simple.

HTML

<html>
<head>
</head>
<body>
    <p>This is a paragraph.</p> 
    <button>Toggle between hide() and show()</button>
</body>
</html>

Javascript

$("button").click(function(){
    $("p").toggle();
});

JSFiddle

The problem is when the form is reloaded the toggle state is forgotten. I would like to use the js-cookie to remember the last toggle state (on or off). How do I use this cookie to remember the state?

You can use local storage of browser to store toggle state.

$("button").click(function(){
    $("p").toggle();
    localStorage.setItem("toggleState","true");
});

var state=localStorage.getItem("toggleState");
if(state=="true"){
console.log("toggled");
}

EDITS:

JS FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM