0

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 !

  • 2
    This code will save a cookie, but on load of page, are you checking for this cookie and loading value from it? It won't happen on its own. – Anurag Srivastava Mar 18 '19 at 10:43
  • Alternative to using cookies => [window.localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) – Tim Vermaelen Mar 18 '19 at 10:45

2 Answers2

2

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

Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
  • In your jsfiddle, you will have troubles if the user uncheck the input and reload the page. – Dwhitz Mar 18 '19 at 10:49
  • 1
    @Dwhitz true, but currently is not apart of the OP question. I will add it in a sec – Carsten Løvbo Andersen Mar 18 '19 at 10:50
  • thanks you so much > but i have this code ( $('.edit-button,.ok-button').toggle(); ) for switching between to image > where i should put it to save also like darkmode ( if you don't got it ) i have two image logo and bgfor website it's related with the dark mode when i click dark mode he should save the dark mode and image for dark mode together >???? and thank u so much for your help –  Mar 18 '19 at 11:11
  • @rabeea I only have the code you posted, and neither you code or text said anything about two image logos, but happy it helps you – Carsten Løvbo Andersen Mar 18 '19 at 11:12
0

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');
}
Vadim
  • 8,701
  • 4
  • 43
  • 50
Deepak A
  • 1,624
  • 1
  • 7
  • 16
  • 1
    you should always add an explanation to why your answer will work. Also if you just copy paste the answer then it's a good idea to link to the answer https://stackoverflow.com/a/25617724/2943218 – Carsten Løvbo Andersen Mar 18 '19 at 10:58