简体   繁体   中英

Why isn't my cookie updating?

I am making a dark mode for a site using a button toggle. To keep the dark mode saved when changing pages, I am using cookies. When pressing the toggle again, the dark mode is disabled but is not saving and I am not sure why.

Ps. I am new at javascript so this may be a dumb mistake.

if ($.cookie('darkModeOn')){
      $('html').toggleClass('dark-mode');

      $('#dark-toggle').click(function(){
      $.cookie('darkModeOn', false, { expires: 7 });
      $('html').toggleClass('dark-mode');
      });
   }
   else
   {
      $('#dark-toggle').click(function(){
      $.cookie('darkModeOn', true, { expires: 7 });
      $('html').toggleClass('dark-mode');
      });
    }

When you press the toggle button you also want to toggle the True/False value of the cookie. Now you always either set it to True or to False depending on the first state.

Use ! $.cookie('darkModeOn') ! $.cookie('darkModeOn') as value to store into the cookie to automatically toggle the boolean value.


EDIT

It was indeed not working, and I found out that it was not working because of the boolean values. The boolean values are stored as string ( "false" and "true" ) since if ( "false") gives boolean true, the if is always executed. When you use integers instead of booleans this would work, but you can also change the if to:

if ($.cookie('darkModeOn')=="true") //...

If you use integers it also works:

https://jsfiddle.net/6m2ydrh2/12/

$('#dark-toggle').click(function(){
       //this gets executed each click so we need to toggle the boolean value.
      if ($.cookie('darkModeOn')==0){
          $.cookie('darkModeOn', 1, { expires: 7 });
      }else{
          $.cookie('darkModeOn', 0, { expires: 7 });
      }
      console.log( "cookie:"+$.cookie('darkModeOn')) ;
      $('#test').toggleClass('dark-mode');
  });
  if ($.cookie('darkModeOn')){
       //this is only executed on load
      $('#test').toggleClass('dark-mode');
  }

See also this post: jquery cookie set value to boolean true . The boolean values are stored as string and therefor causing problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM