Photo by Walling on Unsplash

Automatic Dark Mode with JavaScript

Detecting Users’ OS Dark Mode Preference Using matchMedia()

Faraz Kelhini
The Pragmatic Programmers
2 min readApr 11, 2022

--

https://pragprog.com/newsletter/

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

Often, web designers use the prefers-color-scheme CSS media feature to provide a different theme when dark mode is enabled. prefers-color-scheme obtains the user’s preference through the OS setting or the user agent setting. Here’s a simple example:

/* Style rules for dark mode */
@media (prefers-color-scheme: dark) {
body {
background-color: black;
color: white;
}
}
/* Style rules for light mode */
@media (prefers-color-scheme: light) {
body {
background-color: white;
color: black;
}
}

If you are a JavaScript developer, you might want to programmatically detect whether dark mode is enabled in the user’s operating system and seamlessly adapt your app. In JavaScript, you can takes advantage of the Window interface’s matchMedia() method to check the value of the prefers-color-scheme CSS media feature. Consider this example:

const darkMode = window.matchMedia("(prefers-color-scheme:dark)").matches;

prefers-color-scheme has a value of either dark or light. We pass (prefers-color-scheme:dark) as an argument to the matchMedia() method getting us a MediaQueryList object. Then we read the matches property of the object, which is a Boolean value.

🕶 Dark mode is an extremely useful feature to most users. Take advantage of the matchMedia() method to provide a better experience for your users.

--

--

Faraz Kelhini
The Pragmatic Programmers

Faraz is a professional JavaScript developer who is passionate about promoting patterns and ideas that make web development more productive. Website: eloux.com