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 (highly recommended)
yarn add @nberlette/color-scheme-change
# shorthand for `npm install --save`, saves to dependencies.
npm i -S @nberlette/color-scheme-change
Both CommonJS require
and ECMAscript import
are supported.
import { colorSchemeChange } from '@nberlette/color-scheme-change'
colorSchemeChange((theme) => console.log(`[named] color scheme: ${theme}`))
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.
import colorSchemeChange from '@nberlette/color-scheme-change'
colorSchemeChange((theme) => console.log(`[default] color scheme: ${theme}`))
const { colorSchemeChange } = require('@nberlette/color-scheme-change')
colorSchemeChange((theme) => console.log(`[colorSchemeChange]: ${theme}`))
const { colorSchemeChange: onScheme } = require('@nberlette/color-scheme-change')
onScheme((theme) => console.log(`[onScheme] color scheme: ${theme}`))
const colorSchemeChange = require('@nberlette/color-scheme-change').default
colorSchemeChange((theme) => console.log(`[colorSchemeChange]: ${theme}`))
Listen for changes to the system color scheme in the web browser. Detect when the system switches between Light Mode and Dark Mode.
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.
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.