JavaScript

Detect Dark Mode Preference

by @admin
10h ago
Apr 28, 2026
Public
Reads the user's OS-level dark mode preference using the prefers-color-scheme media query and watches for live changes. Useful for initialising theme state before any user interaction and reacting automatically when the user switches their system theme without reloading the page.
JavaScript
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);
});
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.