https://github.com/andreruffert/color-scheme-switch-element
💡 A simple custom element to toggle between a light and dark page color scheme
https://github.com/andreruffert/color-scheme-switch-element
Last synced: 11 months ago
JSON representation
💡 A simple custom element to toggle between a light and dark page color scheme
- Host: GitHub
- URL: https://github.com/andreruffert/color-scheme-switch-element
- Owner: andreruffert
- License: mit
- Created: 2025-02-25T23:37:47.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2025-04-30T11:58:00.000Z (11 months ago)
- Last Synced: 2025-04-30T13:07:54.299Z (11 months ago)
- Language: JavaScript
- Homepage:
- Size: 181 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# <color-scheme-switch> element
> A simple custom element to toggle between a light and dark page color scheme.
[](https://github.com/andreruffert/color-scheme-switch-element/actions/workflows/test.yml)
[](https://www.npmjs.com/package/color-scheme-switch-element)
[](https://pkg-size.dev/color-scheme-switch-element@latest)
[](https://www.npmjs.com/package/color-scheme-switch-element)
[](https://www.jsdelivr.com/package/npm/color-scheme-switch-element)
## Features
- Toggle between a light and dark color scheme
- Considers system preference
- Persist user preference
**[Demo](https://andreruffert.github.io/syntax-highlight-element)**
## Installation
```shell
npm install color-scheme-switch-element
```
## Usage
### JavaScript
```html
// 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);
// ...
});
```
### Markup
```html
```
### Events
When initially loaded or after switching the color scheme, a `color-scheme-switch` event is dispatched from the `` element.
```js
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](https://andreruffert.com)