简体   繁体   中英

How can i save the dark mode value in browsers ( using jquery )

the idea is I've a dark mode,i done with it ,but the problem ,when i reload the page the dark mode gone

this is HTML code

<input type="checkbox" id="darkMode" name="">

and this is js code ( with this way doesn't run )

var ele = 'body';

  $('#darkMode').on('click',function(){

      if(  $('#darkMode').prop('checked') ){

        $(ele).addClass('dark-mode');

        // here i wanna save the value of darkMode in browser 
        $.cookie('darkMode', 'dark', { expires: 7, path: '/' });

      }else{

        $(ele).removeClass('dark-mode');

      }

  });   

thanks !

You should add something like:

$(document).ready(function() {
  if($.cookie('darkMode')){
    $(ele).addClass('dark-mode');
    $('#darkMode').prop('checked',true)
  }
});

It will check if the cookie exist and if it does then set the darkmode.

Edit

if you want to remove the cookie when you uncheck the checkbox, then use

$.removeCookie('darkMode', {
  path: '/'
});

FiddleTest

You can read cookie of the document, check if darkMode property is present using regular expression and add dark-mode class to the body

if(document.cookie.match(/^(.*;)?\s*darkMode\s*=\s*[^;]+(.*)?$/)) {
  $('body').addClass('dark-mode');
}

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