This is where you can share your code for solving the Dark Mode Toggle exercise ![]()
Okay so the flash of unstyled content is the real enemy here. I’ve seen that script-in-head trick work wonders for killing the flicker.
It’s all about getting that data-theme attribute on the documentElement before the browser even thinks about rendering.
The incentive structure of the browser rendering pipeline is what creates this problem. You’re essentially racing the parser.
Here’s how I’d actually build this one, keeping it simple.
I like the CSS variables approach. Define your colors once on :root, then override them under [data-theme=“dark”]. That way the toggle is just flipping one attribute, not rewriting a bunch of classes.
:root {
--bg: #ffffff;
--text: #111111;
}
[data-theme="dark"] {
--bg: #111111;
--text: #f5f5f5;
}
body {
background: var(--bg);
color: var(--text);
}
For the JS, read the saved choice first, fall back to the system preference, and only then wire up the button:
const root = document.documentElement;
const saved = localStorage.getItem("theme");
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
root.dataset.theme = saved || (prefersDark ? "dark" : "light");
button.addEventListener("click", () => {
const next = root.dataset.theme === "dark" ? "light" : "dark";
root.dataset.theme = next;
localStorage.setItem("theme", next);
});
The bit I’d watch out for is the flash on load. If you only set the theme in your main script at the end of the body, users get a quick blink of light mode. A tiny inline script in the head that sets data-theme before anything paints fixes that, and it’s worth doing even for a small exercise.
Also, keep the button honest: use aria-pressed or update its label so it actually says what will happen next, not just what the current mode is. Small detail, but it makes the toggle feel finished instead of half-done.