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 remembered when the user visits the site the next time. I wouldn't like to use jQuery plugins.
Also I would like to add a parameter to the url on button click like ?title=0
where the number would represent the current state of the element, and the state would be also controllable this way.
Here is an example:
$('#hide').click(function(){
$('h1').toggleClass('hidden');
$(this).text() == 'Hide title' ?
$(this).text('Show title') :
$(this).text('Hide title');
});
.hidden {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<button id="hide">Hide title</button>
<h1>Title</h1>
Note, untested at stacksnippets , which does not allow use of
localStorage
Try utilizing
$.holdReady()
,localStorage
See also Global Variable usage on page reload