So I made a tiny website to try something out and I spent a few hours trying to implement a dark mode to it.
The dark mode is correctly working and all but the problem I encounter is when I reload.
I used local storage and it works fine but for some reason the website when in dark mode changes after 0.1s back to light color even though the variable is still on dark… Could someone help me please, here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>Limsite</title>
<link rel="stylesheet" href="./custom.css" />
<script src="./script.js"></script>
<link rel="icon" href="images/">
</head>
<body>
<button onclick="changeTheme()" class="darkswitch">????</button>
<main>
<h1>Testing title</h1>
<p>hello</p>
</main>
</body>
</html>
:root[data-theme="light"] {
--text: #09110f;
--background: #f4fbf9;
--primary: #44c1a1;
--secondary: #85e0c9;
--accent: #58dfbd;
}
:root[data-theme="dark"] {
--text: #eef6f4;
--background: #040b09;
--primary: #3ebb9c;
--secondary: #1f7a63;
--accent: #20a785;
}
body {
background: var(--background);
color: var(--text);
transition: ease-in;
transition-duration: 0.2s;
}
.darkswitch {
position:absolute;
bottom: 10px;
right: 10px;
height: 50px;
width: 50px;
font-size: 1.6rem;
border-radius: 100px;
background: var(--text);
border: unset;
cursor: pointer;
box-shadow: rgba(0, 0, 0, 0.25) 0px 54px 55px, rgba(0, 0, 0, 0.12) 0px -12px 30px, rgba(0, 0, 0, 0.12) 0px 4px 6px, rgba(0, 0, 0, 0.17) 0px 12px 13px, rgba(0, 0, 0, 0.09) 0px -3px 5px;
}
.darkswitch:active {
transform: scale(0.9);
}
let currentTheme = JSON.parse(localStorage.getItem("theme"));
console.log(currentTheme);
function setTheme() {
document.documentElement.setAttribute('data-theme', currentTheme);
}
function changeTheme() {
if (currentTheme === 'dark') {
currentTheme = 'light';
} else {
currentTheme = 'dark';
}
console.log(currentTheme);
localStorage.setItem("theme", JSON.stringify(currentTheme));
setTheme();
}
window.onload = setTheme();
I tried changing the method I used in javascript to other ones but none worked
Limboll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.