<color-scheme-switch>

Live demo

Getting Started

The <color-scheme-switch> custom element provides a UI for switching between light and dark color schemes.

Features

  • Toggle between light and dark color schemes
  • Respects the user's system color-scheme preference
  • Automatically follows system preference changes
  • Persists explicit user choices
  • Keyboard accessible with Enter and Space

Installation

Install the package from your command line.

npm install color-scheme-switch-element Copy Code

Usage

Add the custom element to your page and listen for the color-scheme-switch event. The event provides the currently active color scheme, which you can use to update your page accordingly.

Setup

Register the event listener before the custom element is defined. This ensures the initial color-scheme-switch event is not missed when the element is registered.

<script> document.addEventListener('color-scheme-switch', event => { // The currently active color scheme. const colorScheme = event.target.value; // Apply the active color scheme. document.documentElement.style.setProperty('color-scheme', colorScheme); // Update the accessible label to describe the action. event.target.setAttribute('aria-label', `Switch to ${colorScheme === 'light' ? 'dark' : 'light'} color scheme`) // ... }); </script> Copy Code

Then load the custom element using a render-blocking module script.

<script type="module" async blocking="render" src="https://cdn.jsdelivr.net/npm/color-scheme-switch-element/+esm"></script> Copy Code

The blocking="render" attribute prevents the page from rendering until the custom element has been registered. This helps prevent a flash of the wrong color scheme during page load.

Markup

Add the custom element wherever you want the color-scheme switcher to appear.

<color-scheme-switch title="Toggle light & dark color scheme"> <!-- ... --> </color-scheme-switch> Copy Code
Documentation