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.
Top comments (10)
Dark mode support is still harder than it should be. Tailwind claims dark mode support out-of-the box but you still have to prefix with
dark:
. DaisyUI makes it a lot easier, no prefixing needed! but still leaves it up to you to do persistence. Local storage works but you can't access it in SSR. If you're using sveltekit a complete solution is described by the author of this video (youtube.com/watch?v=5A21S5mMijI)/Bookmarked 🔥🔥🔥
Thanks
🙏
Useful code snippet.
Thanks 👨🏻💻
Thankyou for the info! very helpful! ;)
I am glad you liked it.
It would be nice if all websites used this as the default color theme. In the evening some website with a pickable dark mode throws flash grenades in my face..
Yup. Or else, they can just change the theme based on the system time (day or night).