This content originally appeared on DEV Community and was authored by Bibek
A few days back, I was wondering how to know if the system theme is dark or light in web using JavaScript and I found a way to detect that.
In this article, I will share the implementation that I used to check the system theme.
We will use the method
matchMedia()
provided by the browser's window interface.matchMedia
method expects amediaQueryString
as a parameter and it will return aMediaQueryList
object.MediaQueryList
object will have a property calledmatches
of Boolean data type.
Code
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
// Dark Mode
}
prefers-color-scheme
is a CSS media feature used to detect the system color theme.
We can also have a listener, if user changes the theme in-between.
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", (event) => {
const theme = event.matches ? "dark" : "light";
});
Let me know in the comments if you are aware of any other way to detect the system theme in web.
Originally published on blog.bibekkakati.me
Thank you for reading 🙏
If you enjoyed this article or found it helpful, give it a thumbs-up 👍
Feel free to connect 👋
Twitter | Instagram | LinkedIn
If you like my work and want to support it, you can do it here. I will really appreciate it.
This content originally appeared on DEV Community and was authored by Bibek
Bibek | Sciencx (2022-07-23T05:23:27+00:00) System Color Theme Check In JavaScript. Retrieved from https://www.scien.cx/2022/07/23/system-color-theme-check-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.