I have completed my portfolio website project and wanted to add local storage so the dark/light themes are saved. Everything works expect one small detail. When i set the theme to light and reload the page i have to click the toggle button twice for it to change back to dark theme. When the theme is set to dark body element’s class changes to either “dark” or “light”.
Here is the code:
HTML
<body class="dark">
</body>
After setting it to light:
<body class="light">
</body>
After page reload:
<body class="dark light">
<body>
JavaScript
const body = document.body;
const toggle = document.getElementById("toggle");
const theme = localStorage.getItem("theme");
if (theme) {
body.classList.add(theme);
}
const toggleButton = () => {
if (body.classList.contains("dark")) {
body.classList.replace("dark", "light");
localStorage.setItem("theme", "light");
} else {
body.classList.replace("light", "dark");
localStorage.setItem("theme", "dark");
}
};
toggle.onclick = toggleButton;
here you can see that after reload body’s class changed to “dark light”
How do i make it so after the page reloads body’s class is set to “light” only?