1

I have added some jquery code on my website that when a user clicks the "Dark Mode" link the elements of the page change colors and are stored on local storage. I found a piece of code here on Stackoverflow HTML5 local storage save .toggleClass and it works fine but when a user visits the website for the first time for some reason the elements that i target with my code lose all the original stying. I checked it and all the classes were deleted. When i clicked the "Dark Mode" button and refreshed the page all the classes were back and the website worked perfectly. Can anyone tell me how to fix it? I don't know why this is happening.

css

.nightmode {
    background: black;
}

.headerNightmode {
    background: #6456A3;
}


jquery


jQuery(document).ready(function($){
    /* Write your Public custom_public jQuery here! */
    var button = $('.menu-item-178 a');
     var container = $('#body.page-template-default').toggleClass(window.localStorage.toggled);
     var containerProfile = $('#body.page-template.page-template-page-tpl-profile').toggleClass(window.localStorage.toggled);
     var containerBlog = $('#body.blog').toggleClass(window.localStorage.toggled);
     var containerHeader = $('.header').toggleClass(window.localStorage.toggledHeader);

    //button click
  button.click(function() {


      if (window.localStorage.toggled != "nightmode" && window.localStorage.toggledHeader != "headerNightmode" ) {
      container.toggleClass("nightmode", true );
      containerProfile.toggleClass("nightmode", true );
      containerBlog.toggleClass("nightmode", true );
          containerHeader.toggleClass("headerNightmode", true );
        window.localStorage.toggledHeader = "headerNightmode";
      window.localStorage.toggled = "nightmode";
   } else {
      container.toggleClass("nightmode", false );
        containerProfile.toggleClass("nightmode", false );
        containerBlog.toggleClass("nightmode", false );
       containerHeader.toggleClass("headerNightmode", false );
        window.localStorage.toggledHeader = "";
      window.localStorage.toggled = "";
   }



  });

});
Billy86
  • 11
  • 2
  • Where are you defining the regular colors? I see night mode being turned off on click of the button but what happens or show until someone clicks the button for the first time. – Nawed Khan Sep 11 '19 at 21:35
  • This is a worpdress site and i am adding a custom javascript code and css. The regular colors are in the theme's css file. The first time someone clicks the button, for example the .headerNightmode is added to the
    , but the class .header which i am targeting is missing. And when i click the button again the .headerNightmode is deleted. After that when i refresh the page all the missing classes that i am targeting appear again on the html.
    – Billy86 Sep 11 '19 at 22:28

0 Answers0