CUBE BURSTSTUDIOS
dark-mode-toggle.zip
Details

Dark Mode Toggle (No Flash)

An accessible theme switch that follows the system setting, remembers the visitor's choice and never flashes white on load.

Category
Web Dev
File
dark-mode-toggle.zip
Size
2.6 KB
Downloads
0
Added
16 Oct 2026
Licence
Free to use, no credit needed (CC0)

#javascript#css#dark mode#theme#accessibility

⚑ Report this

An accessible theme switch that follows the system setting, remembers the visitor's choice and never flashes white on load.

The download has a working demo (index.html) plus the files to copy. The key file is shown below with a Copy button.

theme.js
// Dark Mode Toggle · Cube Burst Studios · CC0
// Follows the system setting until the visitor chooses; remembers the choice. Put the inline snippet from
// index.html in <head> so there's no white flash on load.
const KEY = "theme";
export function initThemeToggle(button) {
	const root = document.documentElement;
	const set = (theme, save) => {
		root.dataset.theme = theme;
		button.setAttribute("aria-pressed", String(theme === "dark"));
		button.querySelector("[data-label]").textContent = theme === "dark" ? "Dark" : "Light";
		if (save) try { localStorage.setItem(KEY, theme); } catch {}
	};
	set(root.dataset.theme || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"), false);
	button.addEventListener("click", () => set(root.dataset.theme === "dark" ? "light" : "dark", true));
	matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => {
		let saved = null;
		try { saved = localStorage.getItem(KEY); } catch {}
		if (!saved) set(e.matches ? "dark" : "light", false);
	});
}

MORE
WEB DEV

View all ↗