Logo Logo
Back to list
WEB

JavaScript: How to create a "Dark Mode" toggle

21. 03. 2026
JavaScript: How to create a "Dark Mode" toggle

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!

Hvala za obisk! Dodajam politiko zasebnosti.

© 2024 Vse pravice pridržane.

Vam je koda pomagala? Če želite podpreti moj trud pri pripravi vodičev in vzdrževanju strani, mi lahko namenite donacijo za kavo.