How to detect dark mode in JavaScript
Detecting the user’s dark mode preference allows you to provide a better user experience by respecting their system settings.
As the creator of CoreUI with over 25 years of JavaScript development experience, I’ve implemented dark mode detection in countless production applications.
The most reliable solution is to use the window.matchMedia() API to check the prefers-color-scheme media query.
This method works across all modern browsers and respects the user’s operating system preferences.
Use window.matchMedia() to detect dark mode preference.
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
if (isDarkMode) {
document.body.classList.add('dark-theme')
} else {
document.body.classList.add('light-theme')
}
The matchMedia() method accepts a media query string and returns a MediaQueryList object. The .matches property returns true when the user’s system is set to dark mode. You can also listen for changes when the user switches themes using addListener() or addEventListener(). This ensures your application responds dynamically to theme changes without requiring a page reload.
Best Practice Note
This is the same approach we use in CoreUI components to provide seamless dark mode support. For better user experience, also provide a manual toggle that overrides the system preference and store the user’s choice in localStorage to persist across sessions.



