Theme Switcher

A simple button pattern for switching between light and dark mode.

There is no dedicated theme switcher component in Basecoat.

Theme switching is handled by window.basecoat.theme and a small inline script that applies the stored mode before styles render.

Usage

HTML + JavaScript

Step 1: Avoid the initial flash

Add this inline script before loading your styles. It applies the stored mode before the page renders.

<script>
  (() => {
    try {
      const stored = localStorage.getItem("themeMode");
      if (stored ? stored === "dark" : matchMedia("(prefers-color-scheme: dark)").matches) {
        document.documentElement.classList.add("dark");
      }
    } catch (_) {}
  })();
</script>

Load basecoat.js or the bundled JavaScript before calling window.basecoat.theme.

Step 2: Add your switcher

<button type="button" aria-label="Toggle dark mode" data-tooltip="Toggle dark mode" data-side="bottom" onclick="window.basecoat.theme.toggle()" class="btn-icon-outline size-8">
  <span class="hidden dark:block">
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
      <circle cx="12" cy="12" r="4" />
      <path d="M12 2v2" />
      <path d="M12 20v2" />
      <path d="m4.93 4.93 1.41 1.41" />
      <path d="m17.66 17.66 1.41 1.41" />
      <path d="M2 12h2" />
      <path d="M20 12h2" />
      <path d="m6.34 17.66-1.41 1.41" />
      <path d="m19.07 4.93-1.41 1.41" />
    </svg>
  </span>
  <span class="block dark:hidden">
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" /></svg>
  </span>
</button>

JavaScript API

window.basecoat.theme.get()
Returns "dark" or "light".
window.basecoat.theme.set(mode)
Sets the mode to "dark" or "light" and stores it in localStorage.themeMode.
window.basecoat.theme.toggle()
Toggles between dark and light mode.
<button type="button" onclick="window.basecoat.theme.toggle()">Toggle theme</button>
<button type="button" onclick="window.basecoat.theme.set('dark')">Set dark theme</button>