Reputation: 349
I wrote a function in jquery using toggleClass. The function is called with a button. I managed to save its result in session storage, so when refreshing the page the dark contrast on the page is saved. The problem occurs when I switch back to toggle state. Then session storage automatically loads the previous setting and as a result I still have the dark contrast on. I tried to write this script in two other ways to make it work properly, but unfortunately without positive result. If any of you will be able to help me, I will be very grateful. I've been trying to understand this for several hours.
My JQuery code:
$(document).ready(function(){
var state = sessionStorage.getItem("toggleState");
if(state == "true"){
$('*').not('div.container *').toggleClass("black-contrast");
$('header').toggleClass("black-contrast-border");
$('img, div.container').toggleClass("overlay");
}
$('#black-contrast').click(function(){
$('*').not('div.container *').toggleClass("black-contrast");
$('header').toggleClass("black-contrast-border");
$('img, div.container').toggleClass("overlay");
});
});
I tried to do it like this:
$(document).ready(function(){
$('*').not('div.container *').toggleClass(sessionStorage.toggled);
$('#black-contrast').on('click',function(){
if (localStorage.toggled != "black-contrast" ) {
$('*').not('div.container *').toggleClass("black-contrast", true );
localStorage.toggled = "black-contrast";
} else {
$('*').not('div.container *').toggleClass("black-contrast", false );
localStorage.toggled = "";
}
});
});
Upvotes: 1
Views: 212
Reputation: 461
I think the problem is with the onclick callback function
You are not toggling the sessionStorage.toggleState
You need to toggle the sessionstorage.toggleState each time user click the button.
Try like this
$(document).ready(function() {
var state = sessionStorage.getItem("toggleState");
if (state == "true") {
$('*').not('div.container *').toggleClass("black-contrast");
$('header').toggleClass("black-contrast-border");
$('img, div.container').toggleClass("overlay");
}
$('#black-contrast').click(function() {
const state = sessionStorage.getItem("toggleState");
state ? sessionStorage.removeItem("toggleState") : sessionStorage.setItem("toggleState");
$('*').not('div.container *').toggleClass("black-contrast");
$('header').toggleClass("black-contrast-border");
$('img, div.container').toggleClass("overlay");
});
});
Upvotes: 2