Sub topic 7
Supporting light, dark and system with localStorage
This chapter assumes you have a Tailwind project where dark: utilities already respond to a .dark class on the <html> element. That means you have configured the class or selector strategy from the earlier chapters, in v3 or v4. It also assumes you know the basics of the DOM and localStorage.
Why three choices
A two-state toggle (light or dark) forces every visitor to pick a side. Many users want the site to follow their operating system and change when the system changes. A better model has three choices:
- Light: always light.
- Dark: always dark.
- System: follow
prefers-color-scheme.
localStorage stores the user's choice between visits. It holds strings only, and it persists until the user or the browser clears it.
One key, two meanings
The design uses a single key, theme, with these rules:
| Stored value | Meaning | Result |
|---|---|---|
| `"light"` | User chose light | No `dark` class |
| `"dark"` | User chose dark | `dark` class added |
| *(no key)* | User chose system, or never chose | Follow the OS setting |
Storing nothing for "system" is deliberate. A first-time visitor and a user who picked "system" behave the same, so you need no special value.
The decision logic
The script from the spine implements this in one expression:
// Run on page load and whenever the user changes the setting
document.documentElement.classList.toggle(
"dark",
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches),
);
// User chooses light mode
localStorage.theme = "light";
// User chooses dark mode
localStorage.theme = "dark";
// User chooses to follow the system again
localStorage.removeItem("theme");classList.toggle(name, force) adds the class when the second argument is true and removes it when false. The condition is true when the saved value is "dark". It is also true when no value is saved and the system prefers dark. A saved "light" makes both parts false, so the class is removed even on a dark system.
A reusable function
Repeating that expression is error-prone. Wrap it in a function and call it after every change:
function applyTheme() {
document.documentElement.classList.toggle(
"dark",
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches),
);
}
function setTheme(choice) {
if (choice === "light" || choice === "dark") {
localStorage.theme = choice;
} else {
localStorage.removeItem("theme");
}
applyTheme();
}
applyTheme();setTheme("system") falls into the else branch and clears the key. Any value other than "light" or "dark" is treated as system, which keeps bad input from being stored.
Wiring up the controls
A <select> is a simple way to show all three options:
<select id="theme-select" class="rounded border bg-white px-2 py-1 dark:bg-gray-800 dark:text-white">
<option value="system">System</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<script>
const select = document.getElementById("theme-select");
select.value = localStorage.theme ?? "system";
select.addEventListener("change", () => setTheme(select.value));
</script>On load, the select shows the saved choice, or "system" when nothing is saved. This script assumes setTheme from the previous block is already defined on the page.
Reacting to system changes
If the user chose "system" and then switches their OS to dark, the page should follow without a reload. Listen for the media query's change event:
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", applyTheme);When a saved choice exists, applyTheme ignores the system value, so this listener is safe to leave on.
Common errors
- Storing
"system"and testing for it later. The"theme" in localStoragecheck then fails, and the page ignores the OS setting. Remove the key instead. - Reading
localStoragewithout a guard. Private browsing modes or blocked storage can throw. Wrap calls intry/catchif you support those cases. - Updating the class but not the control. After a reload the
selectmust read the stored value, as shown above.
Exercise
A user selected "dark", then selects "system" again. Which localStorage call should run, and what determines the page's theme afterward?
Show answer
Call localStorage.removeItem("theme"). With no theme key saved, the page follows window.matchMedia("(prefers-color-scheme: dark)"), so the dark class is present only if the operating system prefers dark.
Exercise
Why does applyTheme produce a light page for a user with a dark operating system who saved "light"?
Show answer
The first condition (localStorage.theme === "dark") is false. The second condition requires !("theme" in localStorage), which is also false because the key exists. Both parts are false, so toggle("dark", false) removes the class.