DEV Community

Cover image for System Color Theme Check In JavaScript
Bibek
Bibek

Posted on

System Color Theme Check In JavaScript

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 a mediaQueryString as a parameter and it will return a MediaQueryList object.

  • MediaQueryList object will have a property called matches of Boolean data type.

Code

if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
    // Dark Mode
}
Enter fullscreen mode Exit fullscreen 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";
   });
Enter fullscreen mode Exit fullscreen mode

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.



Latest comments (10)

Collapse
 
atulcodex profile image
🚩 Atul Prajapati 🇮🇳

Bookmarked 🔥🔥🔥

Collapse
 
bibekkakati profile image
Bibek

Thanks

Collapse
 
atulcodex profile image
🚩 Atul Prajapati 🇮🇳

🙏

Collapse
 
myleftshoe profile image
myleftshoe

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)/

Collapse
 
official_fire profile image
CoderZ90

Thankyou for the info! very helpful! ;)

Collapse
 
bibekkakati profile image
Bibek

I am glad you liked it.

Collapse
 
andrewbaisden profile image
Andrew Baisden

Useful code snippet.

Collapse
 
bibekkakati profile image
Bibek

Thanks 👨🏻‍💻

Collapse
 
maurerkrisztian profile image
Krisztián Maurer

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..

Collapse
 
bibekkakati profile image
Bibek

Yup. Or else, they can just change the theme based on the system time (day or night).