How to detect if dark mode is enabled on a browser using JavaScript

#javascript

Last updated on Nov 20, 2020 by Suraj Sharma



In this tutorial, you will learn how you can write a simple JavaScript function to detect if the dark mode is enabled on your browser.


Nowadays, almost all browsers support the dark mode functionality for their users.


However, Browsers expose a method matchMedia() via the Window object, which returns a MediaQueryList object, which can help in determining if dark mode is enabled.



Using window.matchMedia()


The CSS media query string for determining the dark mode is (prefers-color-scheme: dark),


window.matchMedia('(prefers-color-scheme: dark)').matches

when passed as an argument to the matchMedia() method, returns the MediaQueryList object, with the matches property of the object either set as true or false.


Example:


function isDarkModeEnabled() {
  if (typeof window !== 'undefined' &&
    typeof window.matchMedia !== 'undefined') {

    const mediaQueryString = '(prefers-color-scheme: dark)';

    return window.matchMedia(mediaQueryString).matches;
  } else {
    throw new Error('matchMedia is not supported');
  }
}

isDarkModeEnabled() // true




Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.