In this article, we will learn how to detect system dark mode and also detect color mode change using JavaScript and CSS.
As we spend most of our time in front of our laptops, mobile, etc, the dark mode has become a necessary feature of the web.
Most modern browser like chrome changes the color scheme according to the operating system. And as developers, we can make changes to our site according to the prefers-color-scheme mode of the operating system or the browser.
This article is divided into three parts:
- In the first part, we will detect system dark mode using JavaScript and CSS.
- Second Part, we will detect the color change dynamically using JavaScript.
- And in the third, we will detect the change in system color mode using only CSS and make changes to our properties.
Part 1 : Detect Dark Mode Using JavaScript
With the help of JavaScript and CSS media query, we can easily detect dark color mode in our browser.
First using matchMedia
object , we will check if the browser supports dark mode or not.
Then we will detect if it is in dark mode using prefers-color-scheme media query.
The prefers-color-scheme
media query will help to detect whether the user has requested a dark or light color theme.
window.matchMedia('(prefers-color-scheme: dark)').matches
The above code will return us a boolean as an output. If it returns true
, it means the system is in dark mode else it’s in light mode.
Part 2 : Detect Color Mode Change Dynamically using JavaScript.
If a user changes the mode of the browser while using it, we have to make sure we detect the change using JavaScript.
To detect the changes we have to add a change event-listener to the matchMedia()
method like this:
window.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', event => {
if (event.matches) {
//dark color mode
} else {
//light color mode
}
})
Part 3 : Detect System Color Mode using CSS only
We can also change the CSS property of our website according to the color mode of our Operating System or browser.
To do that we can use the prefers-color-scheme media query like this:
@media (prefers-color-scheme: dark) {
.paragraph { color: white }
}
@media (prefers-color-scheme: light) {
.paragraph { color: black }
}
The code will automatically change the CSS property of the paragraph text according to your system color mode.
GET FULL CODE:
Related Topics: