This is my simple code
function toggleDarkMode() {
let darkTheme= document.body;
darkTheme.classList.toggle("darkMode");
}
It works well, but I can't for the life of me think of a way to save it in local.storage since it's not true or false, it just modifies the css.
I'd like for it to be saved and stay on the previous choice when it opens up next time. Anyone have any ideas?
CodePudding user response:
Use window
property localStorage
to save the theme
value across browser sessions.
Try the following code:
const theme = localStorage.getItem('theme')
if (!theme) localStorage.setItem('theme', 'light') // set the theme; by default 'light'
document.body.classList.add(theme)
CodePudding user response:
here is a way you could do it: Cookies.
function toggleDarkMode() {
let darkTheme= document.body;
darkTheme.classList.toggle("darkMode");
document.cookie = "theme=dark";
}
function toggleLightMode() {
let lightTheme= document.body;
lightTheme.classList.toggle("lightMode");
document.cookie = "theme=light";
}
and then to check:
let theme = document.cookie;
if(theme === 'theme=light'){
let lightTheme= document.body;
lightTheme.classList.toggle("lightMode");
} else if {
let darkTheme= document.body;
darkTheme.classList.toggle("darkMode");
}
CodePudding user response:
A way to do that:
<button onclick="toggleDarkMode()"> toggleDarkMode </button>
const toggleDarkMode = (()=> // IIFE
{
let darkMod_Bool = JSON.parse(localStorage.getItem('darkMode') || 'false'); // initialize page
const darkTheme = document.body;
darkTheme.classList.toggle('darkMode', darkMod_Bool); // initialize darkmode if darkMod_Bool is true
return () => // return your toggleDarkMode() function
{
darkMod_Bool = darkTheme.classList.toggle('darkMode') // this is a function true/false
localStorage.setItem('darkMode', JSON.stringify(darkMod_Bool)) // save dakMode status
}
})();