<theme-switcher>

npm version CI status Minified + gzipped size License Type definitions

<theme-switcher> creates a theme picker, sets data-theme on <html>, and remembers the choice in localStorage. You supply the themes’ colors in your CSS. Every control must offer system, light, and dark; you can add other themes.

This component extends <form-multi-switch>, with the same styling hooks and native keyboard behavior. Drop in an empty element to generate the controls, or supply your own radio markup.

Demos

Project site

The CDN pages show postpublication integration source. They don’t execute the displayed imports or provide live CDN pickers.

Installation

npm install @aarongustafson/theme-switcher

Register the element:

import '@aarongustafson/theme-switcher/define.js';

This module also exports defineThemeSwitcher(). It returns true when a custom-element registry is available and false otherwise. Repeating the same registration is safe; a different constructor under theme-switcher throws.

The package root exports the class without registering it. To register it yourself:

import { ThemeSwitcherElement } from '@aarongustafson/theme-switcher';

customElements.define('theme-switcher', ThemeSwitcherElement);

Use a bundler or an import map to resolve the @aarongustafson/form-multi-switch dependency in a browser. The local demo includes an import map; run npm install before serving the repository.

Basic usage

Generate the controls instead

Drop in an empty element:

<theme-switcher></theme-switcher>

The component creates a <fieldset>, <legend>, and System, Light, and Dark radios. Before upgrade, or if JavaScript fails, this version has no usable controls. Supply your own radios when you need native selection and form submission without JavaScript.

Supply the markup yourself

You can wrap a labeled radio group instead:

<theme-switcher>
  <fieldset>
    <legend>Color theme</legend>
    <label
      ><input type="radio" name="theme" value="system" checked />System</label
    >
    <label><input type="radio" name="theme" value="light" />Light</label>
    <label><input type="radio" name="theme" value="dark" />Dark</label>
  </fieldset>
</theme-switcher>

The browser provides radio selection and form submission. The component adds theme changes, persistence, synchronization, and segmented-control styles. Put the group in a form when you need to submit it. Without JavaScript, these radios still select and submit a value, but they don’t change the page’s theme or save a preference. A server can validate the submitted preference and apply it on the next page load.

Your radios define the choices, group name, and legend. See progressive enhancement for configuration and reset behavior.

Give the page its colors

The component writes the selected value to the <html> element as data-theme:

<html data-theme="system"></html>

It doesn’t add a class, set inline colors, or choose a palette for you. Here’s a small starting point using the browser’s system colors:

:root {
  color-scheme: light dark;
}

:root[data-theme='light'] {
  color-scheme: light;
}

:root[data-theme='dark'] {
  color-scheme: dark;
}

body {
  background: Canvas;
  color: CanvasText;
}

When authoring your themes, use [data-theme='light'] and [data-theme='dark'] as your signals. The system-color example above lets the browser follow the device preference for System, including before the component loads. If you supply fixed palettes instead, scope your prefers-color-scheme rules to [data-theme='system'] (and your no-JavaScript default). Don’t let the media query override an explicit choice.

How preferences are loaded

The first control restores a valid saved site preference before using an author default. It uses:

  1. A valid localStorage preference, unless storage="none" is set.
  2. A valid cookie preference, if cookie is enabled and localStorage is missing, unreadable, or invalid.
  3. The component’s value attribute, including one set through configure({ value }) for generated controls.
  4. The checked authored radio, if the component wraps a radio group.
  5. system.

With storage="none", the first control skips both stores, not the author defaults. A value is valid if the control offers it. Each control must include system, light, and dark.

Selecting system saves the literal string system, not the device’s current light or dark preference. A saved System choice overrides every author default.

The component doesn’t read <html data-theme> as a preference; it writes the result there. Additional controls join the page’s current preference rather than loading their own saved choice.

An existing <html data-theme> is an early rendering result, not a separate preference source. Any head script should use the same storage order and fall back to System. Preference lookup stops at the first valid result, without timestamps or comparison reads. Optional cookie mirroring can still write and verify the cookie.

Checked radios and the generated value attribute keep their native reset defaults even when a saved preference wins. Reset applies and saves that default; it doesn’t restore the saved preference. Assignments to .value before initial theme setup are ignored and aren’t saved, including assignments in a behavior module’s first initializer. To make an explicit runtime change, await ready first. During later reconfiguration or behavior loading, .value assignments are still queued and applied when the control is ready.

Configuration

Attribute Property Default What it does
label label Theme Names a generated group. Use the legend with authored markup.
system-label systemLabel System Labels the default System choice.
light-label lightLabel Light Labels the default Light choice.
dark-label darkLabel Dark Labels the default Dark choice.
storage-key storageKey theme-switcher Names the localStorage entry and, with a bare cookie attribute, the cookie too.
storage storage local Persistence is enabled by default. Set to none to disable all storage operations.
cookie cookie None Adds a cookie mirror and fallback. A bare attribute uses storage-key; a value supplies a separate cookie name.
cookie-max-age cookieMaxAge 31536000 Sets the cookie’s lifetime in seconds (one year by default).
name name Unique generated name Names generated radios for form submission.
value value system for generated controls Attribute supplies an initial choice and, for generated radios, the reset default; property changes the current preference after ready.
choices — System, Light, Dark JSON choices using the base component’s format.
disabled disabled false Prevents user input and form submission without clearing the checked choice.
readonly readOnly false Prevents user changes while keeping the checked choice enabled and included in form submission.
required required false Makes the native radio selection required.
icon-only iconOnly false Visually hides label text; you supply the icons.
script script None Loads an optional behavior module before enhancement completes.

See the <form-multi-switch> API for inherited configuration, choice formats, methods, and behavior modules.

Disabling a control preserves its selection and the applied page theme. Re-enabling it restores native form submission of the checked value. An individually disabled checked choice stays selected until you choose an enabled alternative; you can’t return to the disabled choice until it’s enabled again. API assignments and peer or storage updates can still change a disabled or read-only control’s preference.

Change or translate labels

The three choice *-label attributes apply only to the default generated choices. Use them for your application’s vocabulary or translations. Change label too. With authored markup, edit the legend and labels instead:

<theme-switcher
  lang="fr"
  label="Thème"
  system-label="Appareil"
  light-label="Clair"
  dark-label="Sombre"
></theme-switcher>

Language and direction are inherited from the surrounding markup. With <html lang="ar" dir="rtl">, the component and its native controls use RTL without their own dir attribute. You can also scope language and direction to a wrapper, or set them directly on the component to override its context:

<div lang="ar" dir="rtl">
  <theme-switcher
    label="مظهر الموقع"
    system-label="النظام"
    light-label="فاتح"
    dark-label="داكن"
  ></theme-switcher>
</div>

The label demos show application vocabulary, French labels, and Arabic right-to-left layout.

Extra themes

Include the three standard values and add your own using authored radios, the choices JSON attribute, or configure(). Choice labels are text, not HTML. Supply CSS for each extra palette. The reading-palette demo adds Sepia.

Properties and methods

Name What it does
value Gets the selected value, or null before setup or when the control lacks the page theme. Assign an offered nonempty string after ready to change the preference.
resolvedTheme Read-only resolved value: system becomes light or dark; custom theme values pass through.
state Read-only pending, loading, ready, or error. Nonfatal storage errors don’t set it to error.
ready A promise that resolves after native enhancement and theme setup, or rejects on configuration/enhancement failure.
configure(configuration) Configures generated groups using the base component’s format. Not supported for authored fieldsets.
refresh() Rechecks the connected group and returns its readiness promise. Use it after changing authored markup.

The attribute table above lists reflected properties. Other inherited methods and properties follow the base API.

const switcher = document.querySelector('theme-switcher');
await switcher.ready;

switcher.value = 'dark';
console.log(switcher.resolvedTheme); // "dark"

The setter accepts a nonempty offered value; null and empty values throw. It applies the theme, saves it when persistence is enabled, and synchronizes other connected controls. It doesn’t change the radio’s form-reset default or emit the base component’s user-interaction events.

An optional script attribute piggybacks on the base component’s module contract: initialize(element, { signal }), optionally returning a synchronous cleanup function. That initializer runs before theme setup. Await ready outside the initializer if you need the applied preference. Don’t await ready inside it.

Save and synchronize preferences

The component uses localStorage by default. Add cookie if your server also needs the preference:

<!-- Both stores use "theme-switcher". -->
<theme-switcher cookie></theme-switcher>

<!-- Rename both. -->
<theme-switcher storage-key="site-theme" cookie></theme-switcher>

<!-- Give the cookie its own name. -->
<theme-switcher storage-key="site-theme" cookie="server-theme"></theme-switcher>

<!-- Neither store is read or written, even with cookie present. -->
<theme-switcher storage="none" cookie></theme-switcher>

Cookie settings are also accessible imperatively via the element’s cookie and storageKey properties.

On startup, a valid localStorage value wins over the cookie. A valid cookie is the fallback when localStorage is missing, contains an unsupported theme, or isn’t available. When a saved preference is restored with cookie backing enabled, the component tries to align both stores. User changes update both independently: if either fails, the other can still save the preference. Failures emit diagnostic errors.

Cookies use Path=/, SameSite=Lax, and Secure on HTTPS, with no Domain. Cookie names must be valid cookie-name tokens, and cookie-max-age must be a positive safe integer when storage is enabled. The cookie is readable by JavaScript, so it can’t be HttpOnly. It’s a display preference, not an authorization or security signal. Your server must validate its value against your themes and escape any rendered attribute value before setting the initial <html data-theme>. The component doesn’t implement server-side handling.

With localStorage enabled, other tabs using the same key update through the browser’s storage event. Storage events received while a control is regenerating or booting are applied when the component is ready. Cookie changes are checked on window focus, when the document becomes visible, and through cookieStore change events when that API is available. A removed preference returns to System.

Connected controls in the same document share the page preference even with different storage settings. Peer updates don’t write each peer’s localStorage. If a peer lacks an extra theme, its value becomes null, it reports a nonfatal synchronization error, and the page retains that theme. Selecting an offered theme restores its selection. Include the same choices in all page controls when you need them to stay selected.

Restore a saved choice before first paint

The component can’t apply a saved preference before its module loads. An early head script can reduce a flash of the default palette. Place it before your stylesheets, use the component’s preference order, and fall back to System:

<script>
  let theme;
  try {
    theme = localStorage.getItem('theme-switcher');
  } catch (error) {
    console.warn('Could not restore the saved theme.', error);
  }
  document.documentElement.setAttribute(
    'data-theme',
    ['system', 'light', 'dark'].includes(theme) ? theme : 'system',
  );
</script>

If you’ve enabled cookie backing, read that cookie when localStorage doesn’t provide a valid choice:

<script>
  const key = 'theme-switcher';
  const allowed = ['system', 'light', 'dark'];
  let theme;
  try {
    theme = localStorage.getItem(key);
  } catch (error) {
    console.warn('Could not read the saved theme.', error);
  }
  if (!allowed.includes(theme)) {
    try {
      const prefix = `${key}=`;
      const cookie = document.cookie
        .split(';')
        .map((part) => part.trim())
        .find((part) => part.startsWith(prefix));
      theme =
        cookie === undefined
          ? null
          : decodeURIComponent(cookie.slice(prefix.length));
    } catch (error) {
      console.warn('Could not read the theme cookie.', error);
    }
  }
  document.documentElement.setAttribute(
    'data-theme',
    allowed.includes(theme) ? theme : 'system',
  );
</script>

Use your cookie’s name for prefix if it differs from the localStorage key. Both snippets replace an existing data-theme with System when no valid saved choice is available. That matches a control with no author default. If you deliberately use a different author default, align the early script with it. The component doesn’t treat server-rendered data-theme as a preference source.

Keep the storage key, cookie name, and allowed themes aligned with your configuration. Don’t read either store when using storage="none". With a Content Security Policy, authorize the head script with a nonce or hash; don’t relax the policy to permit arbitrary inline scripts. Also authorize your module sources and import map as required by your policy.

Progressive enhancement

The authored example keeps useful native controls before upgrade and when JavaScript fails. The component’s initial value attribute can select an existing radio without changing its reset default. Unsupported values report a configuration error. Later value attribute changes are ignored; use .value after ready to change the selection.

Other behavior and persistence attributes still apply. configure() is only for generated groups.

The fallback demo shows native form submission without loading the component module.

On disconnect, the component removes its document, storage, media-query, and reset listeners and leaves the page’s last applied theme in place. The base component cleans up its enhancement and behavior module. Reconnecting prepares the group again and joins the page’s current preference or reloads storage.

Events

All component events bubble. Listen for theme-switcher:change when you need access to theme switching behavior rather than radio control interaction:

document.addEventListener('theme-switcher:change', ({ detail }) => {
  console.log(detail.value, detail.resolvedTheme, detail.source);
});
Event detail
theme-switcher:change value, previousValue, resolvedTheme, previousResolvedTheme, source
theme-switcher:ready value, resolvedTheme
theme-switcher:error error, phase

Change sources include initial, user, api, attribute, configuration, reset, storage, sync, and system. Initialization emits a change. Repeatedly applying the same preference and resolved theme doesn’t. Each synchronized control emits its own event, so use a listener on one control if you only need one notification.

Error phases include configuration, storage, and synchronization. Diagnostics also go to console.error. Theme configuration failures reject ready and set state to error; storage and synchronization errors are nonfatal. Inherited enhancement/module failures use form-multi-switch:error.

Handle diagnostics without replacing working controls. Invalid saved values fall through to the next preference source. Theme changes still work when storage is blocked, and subsequent changes retry writes. Fix invalid configuration, then await the new ready promise; an unsupported .value assignment made while ready throws without applying that choice. See the storage-failure fixture for a nonfatal storage diagnostic.

Style it to match your site

The default component styles load automatically in the <form-multi-switch> cascade layer.

The 1.x base defaults to Canvas text on a CanvasText selected background. In forced colors, it uses CanvasText on Canvas with an underline to mark the selection. Automatic color adjustment remains enabled.

Your unlayered CSS can override them:

theme-switcher {
  --multi-switch-radius: 999px;
  --multi-switch-border: #173f63;
  --multi-switch-selected-background: #173f63;
  --multi-switch-selected-color: white;
}

The inherited CSS custom properties are --multi-switch-border, --multi-switch-background, --multi-switch-color, --multi-switch-selected-background, --multi-switch-selected-color, --multi-switch-focus-color, --multi-switch-outline, --multi-switch-outline-offset, --multi-switch-radius, and --multi-switch-padding.

Set --multi-switch-outline to replace the entire focus outline and --multi-switch-outline-offset to adjust its spacing. These apply to the label marked [data-focus] when its radio matches :focus-visible, including in forced colors. Without an override, the outline is solid, 3px wide, and offset by 3px.

Use

The demos show text, CSS icons, icon-only controls, and a pill treatment. See the base component’s styling reference for shared defaults and hooks.

Loading styles under a Content Security Policy

The base component injects a stylesheet. A strict style-src policy must allow it, or you can load the base package’s external stylesheet instead. Give the link id="form-multi-switch-styles" to prevent injection:

<link
  id="form-multi-switch-styles"
  rel="stylesheet"
  href="/assets/form-multi-switch.css"
/>

Copy the base package’s form-multi-switch.css export to your chosen URL.

Accessibility

Maintain text labels even when you hide them visually with icon-only. Decorative SVGs should have aria-hidden="true". Supply icons that remain distinguishable in forced-colors mode. Don’t hide the entire <label> or remove its accessible text.

Native radios provide Tab, arrow-key, and Space interaction, checked state, and form behavior. The default focus outline uses :focus-visible. Preserve clear visual context, sufficient contrast, and a clear selected state when you restyle it.

Hiding the legend visually

If the surrounding content already makes the control’s purpose clear, you can use your own CSS to hide the legend visually while keeping its text as the radio group’s accessible name. For example:

<theme-switcher class="hide-legend" label="Color theme"></theme-switcher>
theme-switcher.hide-legend legend {
  position: absolute;
  inline-size: 1px;
  block-size: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
  border: 0;
}

This works with a generated legend or your own authored <legend>. Keep a meaningful label for generated markup, or text in your authored <legend>. Don’t remove the <legend> or use hidden, aria-hidden="true", display: none, or visibility: hidden to hide it from assistive technology.

Browser support

Use a current browser with custom elements, ES modules, :has(), container queries, cascade layers, and media-query change events. Review the component in your supported browsers and assistive technologies before shipping.

Development

npm install
npm run test:run
npm run test:types
npm run lint
npm run test:coverage
npx playwright install chromium firefox webkit
npm run test:browser
python3 -m http.server 8765

Open /demo/ for examples and /test/browser.html for browser-only checks. Add ?native-reset to the browser-check URL and activate Reset appearance when it appears to test a real reset-button activation.

test:browser runs the existing browser checks and upgrade regressions in Chromium, Firefox, and WebKit without a separate server. It covers keyboard and focus behavior, disabled/read-only controls, form reset and submission, same-document and cross-document synchronization, and the no-JavaScript fallback. Forced-color emulation runs in Chromium only; Windows Contrast themes and manual assistive-technology testing still need real-platform verification.

License

MIT. See LICENSE.