Skip to content
Focsd homeFocsd homeFocsd
Forms

Theme toggle

Lets people choose a light or dark theme, or follow their system, and remembers the choice.

  • Tag: focsd-theme-toggle
  • Pattern: Radio group (light / dark / system)
  • Category: Utility

Example

This panel follows the toggle. On a site, leave out target so the toggle sets the theme on <html>.

Save
HTML
<focsd-theme-toggle
target="#theme-toggle-demo"
storage-key-prefix="docs-demo-"></focsd-theme-toggle>
<focsd-card id="theme-toggle-demo">
<p>
This panel follows the toggle. On a site, leave out <code>target</code> so the toggle
sets the theme on <code>&lt;html&gt;</code>.
</p>
<focsd-button variant="action">Save</focsd-button>
</focsd-card>

Usage

Import the module once, then use the tag like any HTML element. Every framework below renders the same element; see Frameworks for setup.

<script type="module">
import '@focsd-dev/components/focsd-theme-toggle.js';
</script>
<focsd-theme-toggle target="#theme-toggle-demo" storage-key-prefix="docs-demo-"></focsd-theme-toggle>

API

Attributes

AttributePropertyTypeDefault
valuevalueThemeChoicesystem
label-displaylabelDisplay'shown' | 'hidden'shown
targettargetstring—
storage-key-prefixstorageKeyPrefixstringfocsd-
labellabelstring—

Methods

MethodDescription
options()The options, in order.
readTarget(target)The value a target shows now.
applyTo(value, target)Apply a value to the target.
storedValue(value)The value to store for a choice (null removes the key).

Events

EventDescription
changeFired when the user picks a theme; read value.

CSS parts

Style the inside of the component with ::part(), for example focsd-theme-toggle::part(group).

PartDescription
groupThe radio group.
optionEach option.
option-checkedThe checked option.
iconThe icon in each option.
labelThe text of each option.

Accessibility

  • It is a radio group named "Color theme" (or label). Each option has visible text (Light, Dark, System, High contrast) beside its icon, so the choice never depends on the icon alone.
  • The group is one Tab stop. The arrow keys move between the options and choose them, as in any radio group; Home and End go to the first and last. In right-to-left text, Left moves forward.
  • The chosen option shows a border and a bar under it as well as a color change, and a Highlight border in forced-colors mode.
  • System removes data-focsd-theme, so the page follows prefers-color-scheme (and prefers-contrast). The choice is stored as focsd-theme in localStorage; storage that is blocked is ignored.
  • Put the tokens' noFlashScript in the page head so a returning visitor's theme applies before the first paint.

Keyboard

KeyAction
TabMove to the chosen option
Arrow keysMove to the next or previous option and choose it
Home / EndChoose the first or last option