I am using the W3Scholls Dark Mode Toggle for my webiste and it's working perfectly well.
But just after I refresh my page the default view that is Day Mode is shown.
This is Webpage Test Page.
How can I set cookies so that if a user selects dark mode then the page opens in dark mode by default?
Also, How can this be applied for the whole website so that the user need not press the button every time he opens the page.
You could use localStorage
for this.
// On page load set the theme.
(function() {
let onpageLoad = localStorage.getItem("theme") || "";
let element = document.body;
element.classList.add(onpageLoad);
document.getElementById("theme").textContent =
localStorage.getItem("theme") || "light";
})();
function themeToggle() {
let element = document.body;
element.classList.toggle("dark-mode");
let theme = localStorage.getItem("theme");
if (theme && theme === "dark-mode") {
localStorage.setItem("theme", "");
} else {
localStorage.setItem("theme", "dark-mode");
}
document.getElementById("theme").textContent = localStorage.getItem("theme");
}
HTML:
<button type="button" onclick="themeToggle()">Theme Toggle</button>
<div id="theme"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With