How to detect dark mode of the browser in JavaScript

Overview

The matchMedia method is used in the window object to check if the window matches the media query string.

Parameters

We pass (prefers-color-scheme: dark) as a media query string to the matchMedia method. This detects dark-mode.

Return value

This method returns a MediaQueryList object.

The returned object contains two properties and an event.

Properties

  1. matches: This is the Boolean value denoting whether the passed media query is matched or not.
  2. media: This is the passed media query.

Event

  1. Change: This is triggered when the state of the media query changes. For example, dark mode to normal mode.

Code to detect the dark mode

Console
Detecting dark mode in JavaScript

Explanation

  • Line 1: We use the matchMedia method with a dark mode media query (prefers-color-scheme: dark) as an argument. This method will return a MediaQueryList object that is stored in mediaQueryObj variable.

  • Line 2: We access the matches property of the mediaQueryObj. This method will return a Boolean value denoting whether the system is in dark mode.

  • Line 3: We set dark mode status as the text content of the DOM element, status, using the textContent property.

Free Resources