1

I want to create a toggle function for my localStorage as I am trying to install a dark mode on my site and 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 - however I am clearly making some error on my attempt to toggle the localStorage state.

// 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');
});

I know there are various localStorage toggle questions out there but I can't find one quite the same as mine.

DevOverflow
  • 37
  • 1
  • 11
  • 32
  • 1
    "however I am clearly making some error on my attempt to toggle the localStorage state", what exactly makes you say that? What do you expect to happen? What actually happens? – Wesley Smith Nov 15 '20 at 11:28
  • Does this answer your question? [Cannot set boolean values in LocalStorage?](https://stackoverflow.com/questions/3263161/cannot-set-boolean-values-in-localstorage) Basically, you cant store bool values in localstorage, only strings – Wesley Smith Nov 15 '20 at 11:30
  • @WesleySmith it goes true, then false, and stays false thereafter. I want it to toggle back and forth between true and false – DevOverflow Nov 15 '20 at 11:33

1 Answers1

3

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:

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");
});

Pay attention: I use + sign before getting value from localStorage to convert it to Number

QuazBuzz
  • 1,112
  • 1
  • 8
  • 18