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
matches: This is the Boolean value denoting whether the passed media query is matched or not.media: This is the passed media query.
Event
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
Explanation
-
Line 1: We use the
matchMediamethod with a dark mode media query(prefers-color-scheme: dark)as an argument. This method will return aMediaQueryListobject that is stored inmediaQueryObjvariable. -
Line 2: We access the
matchesproperty of themediaQueryObj. 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 thetextContentproperty.