Use
flexiTheme to manage light/dark/system mode with a tiny API. 1. Add Initial Script In <head> (No Flash)
This script runs before your app code, so the correct theme is applied immediately.
It does not depend on any bundler or framework.
<script>
!(function () {
try{const k="flexilla-theme",l="theme",s=localStorage.getItem(k)||localStorage.getItem(l)||"system",m=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",r=s==="system"?m:s,d=document.documentElement;d.classList.toggle("dark",r==="dark");d.setAttribute("data-theme",r);d.style.colorScheme=r}catch(_){}
})();
</script> 2. Initialize Theme Utility
import { flexiTheme } from "@flexilla/utilities";
const theme = flexiTheme({
storageKey: "flexilla-theme",
initialTheme: "system",
});
theme.initTheme(); 3. Use The API
theme.setTheme("dark"); // "light" | "dark" | "system"
theme.toggle(); // toggle between light and dark
theme.getCurrentTheme(); // resolved runtime theme: "light" | "dark"
theme.getTheme(); // saved preference: "light" | "dark" | "system" Options
You can customize the theme utility with:
-
storageKeyto control where the preference is stored -
initialThemeto choose the default preference -
modeto use class mode or attribute mode -
classNamewhen using class mode -
attributeNamewhen using attribute mode -
listenSystemChangesto react to OS theme changes -
suppressTransitionto avoid transition flicker while switching themes
const theme = flexiTheme({
storageKey: "app-theme",
mode: "attribute",
attributeName: "data-theme",
initialTheme: "system",
}); 4. Optional Theme Buttons
<button data-theme-value="light">Light</button>
<button data-theme-value="dark">Dark</button>
<button data-theme-value="system">System</button>
<button id="theme-toggle">Toggle</button> Events
The document element dispatches a
theme-changed event whenever the theme is updated. document.documentElement.addEventListener("theme-changed", (event) => {
console.log(event.detail.theme);
console.log(event.detail.preference);
}); document.getElementById("theme-toggle")?.addEventListener("click", () => {
theme.toggle();
});
document.querySelectorAll("[data-theme-value]").forEach((el) => {
el.addEventListener("click", () => {
const value = el.getAttribute("data-theme-value");
if (value === "light" || value === "dark" || value === "system") {
theme.setTheme(value);
}
});
});