Automatic Dark Mode with JavaScript
Detecting Users’ OS Dark Mode Preference Using matchMedia()
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.
If you enjoyed this article, you may also like Faraz Kelhini’s book, Modern Asynchronous JavaScript. Through May 15, 2022, you can use promo code fkajs_medium_35 to save 35% on the ebook version. Promo codes are not valid on prior purchases.