I created a switch theme button for my website, it only modify the background color of the body and the header.
The html :
<div class="buttonContainer">
<button onclick="SwitchTheme()"></button>
</div>
The js :
function SwitchTheme() {
var element = document.querySelector("body");
element.classList.toggle("dark-mode");
var elementB = document.querySelector("header");
elementB.classList.toggle("nav-dark-mode");
var x = document.getElementById("Sun");
var y = document.getElementById("Moon");
if (x.style.display === "none") {
x.style.display = "block";
y.style.display = "none";
}
else {
x.style.display = "none";
y.style.display = "block";
}
console.log("VarSampleVal")
}
I suggest you store theme a class on cookie, using javascript cookie. so that when the class name existed on the cookie use it as a default theme class.
Then everytime your page reloaded/refreshed, check on the cookie of what class is stored and print it on your class tag.
HTML
<script type="text/javascript">
function SwitchTheme() {
var element = document.querySelector("body");
element.classList.toggle("dark-mode");
var elementB = document.querySelector("header");
elementB.classList.toggle("nav-dark-mode");
var x = document.getElementById("Sun");
var y = document.getElementById("Moon");
if (x.style.display === "none") {
x.style.display = "block";
y.style.display = "none";
// Store Dark Mode Class in Cookie
document.cookie = "my_theme_body_class=dark-mode; path=/";
document.cookie = "my_theme_header_class=nav-dark-mode; path=/";
}
else {
x.style.display = "none";
y.style.display = "block";
// Delete Value Dark Mode Class in Cookie
document.cookie = "my_theme_body_class=; path=/";
document.cookie = "my_theme_header_class=; path=/";
}
console.log("VarSampleVal")
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var el_body = document.querySelector("body");
el_body.classList.add(getCookie('my_theme_body_class'));
var el_header = document.querySelector("header");
el_body.classList.add(getCookie('my_theme_header_class'));
</script>
</body>