I would like to save the state toggled depending what user has selected.
My code looks below:
<div id="wrapper">
stuff here
</div>
<script>
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
</script>
If I had class toggled set to id wrapper then the div is toggled by default.
How can I solve this with a cookie? So It remebers what user has clicked, so it sets the div eighter to toggled or not toggled on page reload.
I am not sure cookies will be the best option. Maybe localStorate is a more viable and easier option.
You can use it like this:
$("#menu-toggle").click(function(e) {
e.preventDefault();
var element = $("#wrapper");
element.toggleClass("toggled");
if (element.hasClass("toggled")) {
localStorage.setItem('toggled', 'true');
} else {
localStorage.setItem('toggled', 'false');
}
});
// On load
var element = $("#wrapper");
var toggled = localStorage.getItem('toggled');;
element.toggleClass("toggled");
if (toggled == "true")
element.addClass("toggled");
else
element.removeClass("toggled");
JSFiddle: https://jsfiddle.net/8tpxx71z/
More info: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
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.