I recently implemented dark mode on my website and it's working flawlessly.
However, every time I refresh the page, it reverts back to the default Day Mode view. Is there a way to save these preferences?
In the HTML section:
<body>
<div class="main-page" id="main-page">
<a id="darkmode" onclick="myFunction()" style="display: block; position: fixed; z-index: 2147483647;"><span><i class="fa fa-moon" id="darkIcon"></i></span></a>
</div>
</body>
And in the JavaScript section:
function myFunction() {
var element = document.getElementById("main-page");
var icon = document.getElementById("darkIcon");
element.classList.toggle("active-dark");
if (element.className == ["main-page active-dark"]){
if (icon.className == "fa fa-moon"){
icon.classList.toggle("fa-sun");
}else {
icon.classList.toggle("fa-moon");
}
}
if (element.className == "main-page"){
if (icon.className == "fa fa-sun"){
icon.classList.toggle("fa-moon");
}else {
icon.classList.toggle("fa-sun");
}
}
}
Please Note:
To switch to dark mode, simply add "active-dark" after the "main-page" class, and to go back to light mode, remove the class.