Dark Mode is no longer just a trend; it's a standard for a better user experience, especially at night. Let's look at how to allow users to choose their own theme using simple JavaScript.
1. HTML Button
First, we need a button in our navbar to trigger the theme change.
<button id="theme-toggle" onclick="toggleTheme()">
🌓
</button>
2. CSS and Attributes
Instead of changing colors for each element individually, we define CSS variables based on the data-theme attribute on the <html> element.
:root { --bg: #ffffff; --fg: #000000; }
[data-theme="dark"] { --bg: #121212; --fg: #ffffff; }
body { background: var(--bg); color: var(--fg); }
3. JavaScript Logic
The main task is handled by JavaScript. The function toggles the attribute and saves the choice in localStorage, so the browser remembers the setting for the next visit.
function toggleTheme() {
const root = document.documentElement;
const current = root.getAttribute("data-theme");
const next = (current === "dark") ? "light" : "dark";
root.setAttribute("data-theme", next);
localStorage.setItem("theme", next);
}
With this simple trick, your site will be modern and eye-friendly for your visitors!