Detect Preferred Color Scheme 🐛️ 🔍️ 👀️
A micro ES6 module (~0.5KB) for detecting a users preferred-color-scheme
and watching for changes.

Installation
npm install @egstad/detect-theme
Usage
import theme from '@egstad/detect-theme'
window.addEventListener('colorSchemeUpdated', (e) => {
switch (e.detail.theme) {
case 'dark':
break;
case 'light':
break;
default:
break;
}
})
theme.watch()
Methods
The watch()
method is more than likely all you'll need. Here's a list of what each method in the module does.
theme.get()
theme.watch()
theme.destroy()
Example
Here is a screencap demonstrating the realtime updates on Mac OS (System Preferences > General > Appearance).

Example: Editing CSS Variables on colorSchemeUpdated
window.addEventListener('colorSchemeUpdated', (e) => {
switch (e.detail.theme) {
case 'dark':
root.style.setProperty('--background', 'black');
root.style.setProperty('--foreground', 'white');
break;
case 'light':
root.style.setProperty('--background', 'white');
root.style.setProperty('--foreground', 'black');
break;
default:
root.style.setProperty('--background', '#D11D05');
root.style.setProperty('--foreground', '#D1E5E1');
break;
}
})