- Instant help with your JavaScript coding problems

Detect Dark Mode in JavaScript

Question:
How to detect Dark Mode in JavaScript?
Answer:
let darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
Description:

Detecting the system-wide dark mode in JavaScript is easy with the matchMedia method. This method has been available in all browsers for almost a decade now, so using it shouldn't be a problem anymore. Media features describe specific characteristics of the user agent. The prefers-color-scheme CSS media feature is used to detect if a user has requested light or dark color themes. A user indicates their preference through an operating system setting (e.g. light or dark mode) or a user agent setting.

let darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
console.log('Is dark mode: ' + darkMode);
Share "How to detect Dark Mode in JavaScript?"
Related snippets:
Tags:
detect, check, dark, light, mode, javascript
Technical term:
Detect Dark Mode in JavaScript