JS Coding Questions Logo
JS Coding Questions
#468💼 Interview💻 Code

How to detect system dark mode in javascript?

Advertisement

728x90

The combination of Window.matchMedia() utility method along with media query is used to check if the user has selected a dark color scheme in their operating system settings or not. The CSS media query prefers-color-scheme needs to be passed to identify system color theme.

The following javascript code describes the usage,

javascript
1const hasDarkColorScheme = () =>
2
3window.matchMedia &&
4
5window.matchMedia("(prefers-color-scheme: dark)").matches;

You can also watch changes to system color scheme using addEventListener,

javascript
1window
2  .matchMedia("(prefers-color-scheme: dark)")
3  .addEventListener("change", (event) => {
4  const theme = event.matches ? "dark" : "light";
5  });

Note: The matchMedia method returns MediaQueryList object stores information from a media query.

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 40

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
468of476