The matchMedia
method is used in the window
object to check if the window matches the media query string.
We pass (prefers-color-scheme: dark)
as a media query string to the matchMedia
method. This detects dark-mode.
This method returns a MediaQueryList
object.
The returned object contains two properties and an event.
matches
: This is the Boolean value denoting whether the passed media query is matched or not.media
: This is the passed media query.Change
: This is triggered when the state of the media query changes. For example, dark mode to normal mode.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.