Skip to content

nberlette/color-scheme-change

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

📦 @nberlette/color-scheme-change

Detect when a user's system color scheme has changed, allowing your site to change virtually simultaneously, making them feel right at home. Setup and implementation only takes a minute or two.

yarn add @nberlette/color-scheme-change npm install @nberlette/color-scheme-change Try on RunKit!


💿 Installation

Yarn (highly recommended)

yarn add @nberlette/color-scheme-change
# shorthand for `npm install --save`, saves to dependencies.
npm i -S @nberlette/color-scheme-change

Usage and Examples

Both CommonJS require and ECMAscript import are supported.

🟨 ES Module (import, .mjs)

"Named" import
import { colorSchemeChange } from '@nberlette/color-scheme-change'

colorSchemeChange((theme) => console.log(`[named] color scheme: ${theme}`))
"Aliased" import

This is preferred over default imports, and has essentially the same effect. You can name it whatever you like.

import { colorSchemeChange as onScheme } from '@nberlette/color-scheme-change'

onScheme((theme) => console.log(`[aliased] color scheme: ${theme}`))

Note: @nberlette/color-scheme-change will work with both default and named ES imports. That being said, the official ECMA specification now recommends named imports whenever possible.

"Default" import
import colorSchemeChange from '@nberlette/color-scheme-change'

colorSchemeChange((theme) => console.log(`[default] color scheme: ${theme}`))

🟩 CommonJS Module (require, .cjs)

Recommended import (Object Destructuring)
const { colorSchemeChange } = require('@nberlette/color-scheme-change')

colorSchemeChange((theme) => console.log(`[colorSchemeChange]: ${theme}`))
Alternative: aliased method name
const { colorSchemeChange: onScheme } = require('@nberlette/color-scheme-change')

onScheme((theme) => console.log(`[onScheme] color scheme: ${theme}`))
Default import
const colorSchemeChange = require('@nberlette/color-scheme-change').default

colorSchemeChange((theme) => console.log(`[colorSchemeChange]: ${theme}`))

API

remove = colorSchemeChange(onChange)

Listen for changes to the system color scheme in the web browser. Detect when the system switches between Light Mode and Dark Mode.

onChange

A callback function of the following form: function(colorScheme) {} where colorScheme is either 'light' or 'dark'. The function is called whenever the system enters Light Mode or Dark Mode, respectively.

remove

When the returned remove function is called, all event listeners are cleaned up and the onChange function will no longer be called when the system color scheme changes.