Detect Dark Mode Using Javascript

You can detect if a website is using dark-mode using the prefers-color-scheme media query and checking if its value is dark.

Within the Browser, the window.matchMedia method returns a new MediaQueryList object representing the parsed results of the specified media query string. This returned MediaQueryList can then be used to determine if the Document matches the media query, or to monitor a document to detect when it matches or stops matching the media query.

If you want to check if dark-mode is enabled somewhere in your code, you would simply check if matchMedia exists on the browser and check if it has prefers-color-scheme set to dark.
Like this:

if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    // do something here
}

To perform some actions based on the current state of prefers-color-scheme, you can attach an eventListener to the change event on the matchMedia object like this:

const darkModeListener = (event) => {
  if (event.matches) {
    // this is dark mode
  } else {
    // this is not dark mode
  }
};

window
  .matchMedia('(prefers-color-scheme: dark)')
  .addEventListener('change', darkModeListener);

Of course, you should call removeEventListener somewhere in your code, when you no longer need this function to avoid memory leaks.

Show Comments