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.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to sort an array of objects by string property value in JavaScript
How to sort an array of objects by string property value in JavaScript

What are the three dots `...` in JavaScript do?
What are the three dots `...` in JavaScript do?

How to limit items in a .map loop in JavaScript
How to limit items in a .map loop in JavaScript

How to Open Link in a New Tab in HTML?
How to Open Link in a New Tab in HTML?

Answers by CoreUI Core Team