Automatic Dark Mode with JavaScript
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.
What Now?
Here’s a simple example code css:
/* 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 Dervic Blog's.
Comments (0)