For example, the new Stack Overflow feature, Dark Mode has an option to use the system default between light mode and dark mode. How do they tell what the system default is with JavaScript? And if not with JavaScript, how do you find it?
Asked
Active
Viewed 835 times
0
-
https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme – jonrsharpe Mar 30 '20 at 20:43
-
Does that work on mobile too? – yogurtsyum Mar 30 '20 at 20:44
-
https://caniuse.com/#feat=prefers-color-scheme – jonrsharpe Mar 30 '20 at 20:45
-
Does this answer your question? [How do I detect dark mode using JavaScript?](https://stackoverflow.com/questions/56393880/how-do-i-detect-dark-mode-using-javascript) – Fcmam5 Mar 30 '20 at 20:47
1 Answers
0
Use window.matchMedia
to detect the user's preferred color scheme with JavaScript.
const result = window.matchMedia('(prefers-color-scheme: dark)');
console.log(result.matches); // TRUE if user prefers dark mode

mfluehr
- 2,832
- 2
- 23
- 31