Ship internal tools in hours, not weeks. Real auth, users, jobs, audit logs, and cohesive UI included. Early access $249 $499 → [Get it now]

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 Clone an Object in JavaScript
How to Clone an Object in JavaScript

What is the difference between sort and toSorted in JavaScript?
What is the difference between sort and toSorted in JavaScript?

How to replace all occurrences of a string in JavaScript?
How to replace all occurrences of a string in JavaScript?

How to conditionally add attributes to React components
How to conditionally add attributes to React components

Answers by CoreUI Core Team