I've written a code that instead of incorporating a light/dark mode, it incorporates a spring/summer/autumn/winter mode. Here is an example of one season:
const springThemeOn = sessionStorage.getItem("springtheme")
if (springThemeOn==="true"){
document.body.className = "spring-theme";
spring.classList.add('hide-icon');
summer.classList.remove('hide-icon');
autumn.classList.remove('hide-icon');
winter.classList.remove('hide-icon');
}
//spring change
springIcon.addEventListener('click', () => {
document.body.classList.toggle('spring-theme');
spring.classList.toggle('show-icon');
summer.classList.toggle('show-icon');
autumn.classList.toggle('show-icon');
winter.classList.toggle('show-icon');
// Store toggle info between pages
if (document.body.className.includes("spring-theme")){
// Currently in spring mode
sessionStorage.setItem("spring-theme", "true")
} else {
// Currently in other mode
sessionStorage.setItem("spring-theme", "false")
}
})
Imagine this with all four seasons.
The code works, but when I click on each icon respectively, they each add themselves to the body class like so: <body class="b-page spring-theme summer-theme autumn-theme winter-theme"> and only displays the last clicked on mode.
I want to be able to switch through all four icons and not have to click on/off each icon in order to add/remove them from the class body. I do not want them to stack in the class body. Is there a fix for this? Thank you!
Instead of having a storage item for each theme, have them all share a single storage item.
const theme = sessionStorage.getItem("theme");
if (theme === 'spring') {
// ...
} else if (theme === 'summer') {
// ...
}
// etc
And in the click listener, something like:
if (document.body.className.includes("spring-theme")){
sessionStorage.setItem('theme', ''); // remove any existing themes
} else {
sessionStorage.setItem('theme', 'spring'); // add it
}
This way, there won't be any collisions.