Toggle Theme Switcher
by Newton Anbarasu
HTML
<html data-theme="light">
<body>
<button
type="button"
data-theme-toggle
aria-label="Click to dark theme">Click to Dark theme</button>
</body>
</html>
CSS
[data-theme="light"] {
--color-bg: #ffffff;
--color-fg: #000000;
}
[data-theme="dark"] {
--color-bg: #000000;
--color-fg: #ffffff;
}
body {
background-color: var(--color-bg);
color: var(--color-fg);
display: grid;
min-height: 100vh;
place-items: center;
}
button {
font-size: 2rem;
font-weight: bold;
padding: 0.5rem 1rem;
transition: all var(--global-transition-time) ease-in-out;
border-radius: 2rem;
cursor: pointer;
color: var(--color-fg);
background-color: var(--color-bg);
border: 0.25rem solid var(--color-fg);
}
JavaScript
const button = document.querySelector("[data-theme-toggle]");
const currentTheme = localStorage.getItem("theme");
const systemDark = window.matchMedia("(prefers-color-scheme: dark)");
let themeSetting = getTheme({ currentTheme, systemDark });
function getTheme({ currentTheme, systemDark }) {
return currentTheme !== null ? currentTheme : systemDark.matches ? "dark" : "light";
}
function updateButtonLabel({ buttonEl, isDark }) {
const changeTitle = isDark ? "Click to light theme" : "Click to dark theme";
buttonEl.setAttribute("aria-label", changeTitle);
buttonEl.innerText = changeTitle;
}
function updateHtmltheme({ theme }) {
document.querySelector("html").setAttribute("data-theme", theme);
}
updateButtonLabel({ buttonEl: button, isDark: themeSetting === "dark" });
updateHtmltheme({ theme: themeSetting });
button.addEventListener("click", () => {
const newTheme = themeSetting === "dark" ? "light" : "dark";
localStorage.setItem("theme", newTheme);
updateButtonLabel({ buttonEl: button, isDark: newTheme === "dark" });
updateHtmltheme({ theme: newTheme });
themeSetting = newTheme;
});