How to Detect Dark Mode in JavaScript?

Every website, web app, and mobile app offers a dark mode. The dark mode is helpful while doing late-night coding or worse, trading into altcoins. We can detect dark mode using the prefers-color-scheme media query. But what if we have to use JavaScript? Let us find out.

Detecting dark mode in JavaScript

To detect dark mode using JavaScript, we use the window.matchMedia API. The window.matchMedia API is a JavaScript utility that checks if a document matches a given media query. I am habituated to using this for things like the responsive web, but with the introduction of Dark Mode, I have more freedom.

We have to provide a query to our matchMedia and pass in the prefers-color-scheme with a value of dark or light as follows:

if (window.matchMedia) {
const query = window.matchMedia('prefers-color-scheme: dark');
}

If the user has set the system to dark mode, the value of the query will look like this:

MediaQueryList { media: ‘(prefers-color-scheme: dark)’, matches: true, onchange: null }

Here we can see that we have a MediaQueryList instance with matching properties. If true, the user prefers dark mode. What then? Toggle classes here. Perhaps in tag.

Wrapping things up into functions can be condensed into something simple:

constisDarkMode = () =>
window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches;

How to detect dark mode when the user changes the mode while using the website?

Users can switch between light and dark modes while using the website. How can you detect the dark mode using JavaScript in this case? You can detect the change in the mode using an event listener. Below is the code that demonstrates the same:

window.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', event => {
if (event. matches) {
//dark mode
} else {
//light mode
}
})

End Takeaway

You can come across various questions while learning a programming language. Questioning and seeking answers is the best way to learn. We hope that this tutorial was helpful to you. Keep coding!