Skip to content

Instantly share code, notes, and snippets.

@AliAlmasi
Last active October 1, 2024 21:11
Show Gist options
  • Save AliAlmasi/24bce76ddbc122efb49e35ea5094de34 to your computer and use it in GitHub Desktop.
Save AliAlmasi/24bce76ddbc122efb49e35ea5094de34 to your computer and use it in GitHub Desktop.
Dark Mode w/ JS
<html data-theme="light">
<head>
<title>Dark Mode w/ JS</title>
<style>
[data-theme="light"] {
--color-bg: #e5e5e5;
--color-fg: #0f0f0f;
}
[data-theme="dark"] {
--color-bg: #0f0f0f;
--color-fg: #e5e5e5;
}
* {
font-family: monospace;
}
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);
}
</style>
</head>
<body>
<button type="button" data-theme-toggle aria-label="Change to light theme">
Change to light theme
</button>
<script>
function calculateSettingAsThemeString({
localStorageTheme,
systemSettingDark,
}) {
if (localStorageTheme !== null) {
return localStorageTheme;
}
if (systemSettingDark.matches) {
return "dark";
}
return "light";
}
function updateButton({ buttonEl, isDark }) {
const newCta = isDark
? "Change to light theme"
: "Change to dark theme";
buttonEl.setAttribute("aria-label", newCta);
buttonEl.innerText = newCta;
}
function updateThemeOnHtmlEl({ theme }) {
document.querySelector("html").setAttribute("data-theme", theme);
}
const button = document.querySelector("[data-theme-toggle]");
const localStorageTheme = localStorage.getItem("theme");
const systemSettingDark = window.matchMedia(
"(prefers-color-scheme: dark)"
);
let currentThemeSetting = calculateSettingAsThemeString({
localStorageTheme,
systemSettingDark,
});
updateButton({
buttonEl: button,
isDark: currentThemeSetting === "dark",
});
updateThemeOnHtmlEl({ theme: currentThemeSetting });
button.addEventListener("click", (event) => {
const newTheme = currentThemeSetting === "dark" ? "light" : "dark";
localStorage.setItem("theme", newTheme);
updateButton({ buttonEl: button, isDark: newTheme === "dark" });
updateThemeOnHtmlEl({ theme: newTheme });
currentThemeSetting = newTheme;
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment