function getColorScheme() {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function onColorSchemeChange(callback) {
const mq = window.matchMedia('(prefers-color-scheme: dark)');
const handler = (e) => callback(e.matches ? 'dark' : 'light');
mq.addEventListener('change', handler);
return () => mq.removeEventListener('change', handler); // returns cleanup fn
}
// Usage
console.log(getColorScheme()); // 'dark' or 'light'
const unsubscribe = onColorSchemeChange((scheme) => {
document.documentElement.setAttribute('data-theme', scheme);
});
Create a free account and build your private vault. Share publicly whenever you want.