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