PASSWORD RESET

Your destination for complete Tech news

How to detect dark mode in Javascript?

956 0
< 1 min read

You can detect whether the user’s operating system or device is currently in dark mode by checking the prefers-color-scheme media query in JavaScript. This media query provides information about the user’s preference for light or dark color schemes. Here’s how you can use it:

// Check if the user prefers dark mode
function isDarkMode() {
  return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
}

// Example usage
if (isDarkMode()) {
  console.log('Dark mode is enabled.');
} else {
  console.log('Dark mode is not enabled.');
}

In this example, the isDarkMode() function checks if the user’s preference is set to dark mode using the matchMedia() function and the prefers-color-scheme: dark media query.

Keep in mind that the availability of this feature depends on the browser and device, and it may not work on older browsers. Also, users can manually override the system’s color scheme preference in some cases, so this method might not always accurately reflect the actual appearance of your website or application.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.