A One Minute Guide For Your Automatic Dark Mode Feature with JavaScript(2022)

Using matchMedia() to Determine User's OS Dark Mode Preference

Table of contents

No heading

No headings in the article.

Detecting the OS Dark Mode Preference of Users Making use of matchMedia ()

The dark mode is one of the most requested features in applications. Dark mode provides a more eye-friendly interface with fewer white tones that can cause eyestrain for many users. On AMOLED screens, dark mode is also known to save battery life.

When dark mode is enabled, web designers frequently use the prefers-color-scheme CSS media feature to provide a different theme. prefers-color-scheme obtains the user's preference via the operating system or the user agent setting.

Here's an easy example:

1.png

If you're a JavaScript developer, you might want to detect whether dark mode is enabled in the user's operating system and adapt your app accordingly. To check the value of the prefers-color-scheme CSS media feature in JavaScript, use the Window interface's matchMedia() method.

Consider the following example:

2.png

The value of prefers-color-scheme is either dark or light. We pass (prefers-color-scheme:dark) to the matchMedia() method, which returns a MediaQueryList object. Then we read the object's matches property, which is a Boolean value.

Most users will find dark mode to be extremely useful.

Make use of the matchMedia() method to give your users a better experience.