Toggling localStorage item

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 97

Toggling localStorage item

I want to create a toggle function for my localStorage where I want it to remember the user's choice.
I want it load the current preference on page load, if one has been made, and then toggle the state on click.

My code is below, but it's not working.

Code: Select all

// ON PAGE LOAD, IF USER PREFERS DARK, ADD DARK CLASS TO HTML
if (window.localStorage.getItem('preferDark')) {
 $('html').toggleClass('dark');
}

// TOGGLE STATE ON CLICK
$('.wrapper').click(function(){
  if (window.localStorage.getItem('preferDark', true)) {
    window.localStorage.setItem('preferDark', false);  
} else {
    window.localStorage.setItem('preferDark', true); 
  }
  $('html').toggleClass('dark');
});

Admin
You can't keep boolean in localStorage. That's why you have an error. Try to keep, for example, 0 for False and 1 for True. But remember that localStorage also can't keep integer - you can pass integer or boolean but it will be converted to string.

Try this:

Code: Select all

if (+ window.localStorage.getItem('preferDark')) {
  $('html').toggleClass('dark');
}

$('.wrapper').click(function () {
  if (+ window.localStorage.getItem('preferDark')) {
    window.localStorage.setItem('preferDark', 0);
  }
  else {
    window.localStorage.setItem('preferDark', 1);
  }
  $('html').toggleClass('dark');
});
Note: I use + sign before getting value from localStorage to convert it to Number.

Similar Topics