Page 1 of 1

Toggling localStorage item

Posted: 16 Nov 2020, 15:17
by Marius
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');
});

Toggling localStorage item

Posted: 16 Nov 2020, 17:40
by 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.