Photo by Walling on Unsplash

Automatic Dark Mode With JavaScript

Detecting Users’ OS Dark Mode Preference Using matchMedia()

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Faraz Kelhini

Faraz Kelhini

146 Followers

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