Managing cookies in JavaScript is ugly unless you use a framework. The benefit of using a cookie is that you don't have to worry about compatibility with old browsers. However, if you don't care about old browsers then you can use HTML5 Local Storage (aka Web Storage), which allows you to persist basic key/value pairs of strings.
HTML5 Local Storage (Web Storage) example
Demo: http://jsfiddle.net/9zsH4/
In the demo, try toggling the menu then refresh the page to see its state be persisted.
function getVisible(){
var value = localStorage.getItem('visible');
return value == '1';
}
function setVisible(visible){
localStorage.setItem('visible', (visible ? '1' : '0'));
}
function menu(id)
{
if(!getVisible()) {
document.getElementById(id).style.display = "block";
setVisible(true);
} else {
document.getElementById(id).style.display = "none";
setVisible(false);
}
}
Cookie Example
This example uses the minimal framework from MDN here, so be sure to include the docCookies
framework.
function getVisible(){
var value = docCookies.getItem('visible');
return value == '1';
}
function setVisible(visible){
docCookies.setItem('visible', (visible ? '1' : '0'), new Date(2015, 5, 12));
}
function menu(id)
{
if(!getVisible()) {
document.getElementById(id).style.display = "block";
setVisible(true);
} else {
document.getElementById(id).style.display = "none";
setVisible(false);
}
}
Edit: to explain this line:
localStorage.setItem('visible', (visible ? '1' : '0'));
Here I'm using the ternary operator. It's just a shorthand if/else, so it's the same as doing:
if(visible){
localStorage.setItem('visible', '1');
} else {
localStorage.setItem('visible', '0');
}
Another example: get a human Yes/No representation of a boolean.
var something = true;
var humanText = something ? 'Yes' : 'No';
console.log(humanText); // Yes
var something = false;
var humanText = something ? 'Yes' : 'No';
console.log(humanText); // No
As you can see, the first part is evaluated and if the result equates to true
, the question mark part is used, else the colon part is used.
See this question for more examples.