I have a button on my website that toggles the visibility of an element with jQuery.
How can I store the state of this element in a cookie or local storage? So it is
Note, untested at stacksnippets , which does not allow use of localStorage
Try utilizing $.holdReady()
, localStorage
$.holdReady(true);
// hide title
if (location.search === "?title=0") {
if (!localStorage.getItem("title")) {
localStorage.setItem("title","0");
} else {
localStorage.setItem("title","0");
}
$("#hide").text("Show title");
$("h1").addClass("hidden");
// location.search = "?title=0";
}
// show title
if (location.search === "?title=1") {
if (!localStorage.getItem("title")) {
localStorage.setItem("title","1");
} else {
localStorage.setItem("title","1");
}
$("#hide").text("Hide title");
$("h1").removeClass("hidden");
// location.search = "?title=1"
}
$.holdReady(false);
$(document).ready(function() {
$('#hide').click(function() {
$('h1').toggleClass('hidden');
$(this).text() == 'Hide title' ?
$(this).text('Show title') && localStorage.setItem("title", "0") :
$(this).text('Hide title') && localStorage.setItem("title", "1");
});
location.search = "?title=" + localStorage.getItem("title");
});
See also Global Variable usage on page reload