Reputation: 57
$(document).ready(function() {
var state = localStorage.hasOwnProperty('sidebarState') ? localStorage.getItem('sidebarState') : false;
function setState() {
if(state) {
$('#sidebar').css('transform', 'translate(0,0)');
state = false;
}
else {
$('#sidebar').css('transform', 'translate(-100%,0)');
state = true;
}
localStorage.setItem('sidebarState',state);
}
$('#sidebar_button').click(setState);
setState();
});
Always when I reload the page this return true, even if it is false before, so what is wrong.
Upvotes: -1
Views: 101
Reputation: 216
localStorage.setItem
takes two strings. So the boolean false will be coerced into the string "false", which will evaluate to true.
One fix would be
localStorage.setItem('sidebarState', state ? state : "");
since an empty string will evaluate to false.
Source:
http://dev.w3.org/html5/webstorage/#storage
Upvotes: 3
Reputation: 157
I suspect you are setting the state to true, then persisting it to localStorage with
localStorage.setItem('sidebarState',state);
When you refresh the page, state is read in from localStorage and evaluates to true.
Upvotes: 0