Skip to content

💡 A simple custom element to toggle between a light and dark page color scheme

License

Notifications You must be signed in to change notification settings

andreruffert/color-scheme-switch-element

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

60 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

<color-scheme-switch> element

A simple custom element to toggle between a light and dark page color scheme.

Test status npm version gzip size npm downloads jsDelivr hits (npm)

Features

  • Toggle between a light and dark color scheme
  • Considers system preference
  • Persist user preference

Demo

Installation

npm install color-scheme-switch-element

Usage

JavaScript

<script>
  // Ensure the event listener is setup before the initial `color-scheme-switch` event gets dispatched.
  document.addEventListener('color-scheme-switch', event => {
    const colorScheme = event.target.value;

    // Set the page color scheme e.g
    document.documentElement.style.setProperty('color-scheme', colorScheme);
    // ...
  });
</script>
<script type="module" async blocking="render" src="https://unpkg.com/color-scheme-switch-element@latest/dist/color-scheme-switch-element.js"></script>

Markup

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

Events

When initially loaded or after switching the color scheme, a color-scheme-switch event is dispatched from the <color-scheme-switch> element.

document.addEventListener('color-scheme-switch', event => {
  const button = event.target;
  const colorScheme = event.target.value;

  // Set page color scheme, update aria-label, icon, etc.
})

License

Distributed under the MIT license. See LICENSE for details.

© André Ruffert

About

💡 A simple custom element to toggle between a light and dark page color scheme

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Contributors 2

  •  
  •