Home > Article > Web Front-end > How Can I Detect Dark Mode in JavaScript?
Detecting Dark Mode in JavaScript
With the introduction of dark mode in Windows and macOS, developers face the challenge of adapting CSS and JavaScript styles to match the user's preferred color scheme. This question explores how to detect dark mode in JavaScript, allowing for responsive color scheme adjustments.
Media Query Approach
For CSS, media queries provide a simple solution:
@media (prefers-dark-interface) { color: white; background: black }
JavaScript Detection
The Stripe Elements API, used to create payment elements, requires color specification in JavaScript. To detect dark mode in this context, one needs to leverage the JavaScript API:
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { // dark mode }
This query checks if the window.matchMedia API is supported and evaluates the media query string. If true, the system prefers dark mode.
Watching for Color Scheme Changes
To handle dynamic changes in the color scheme, one can subscribe to the change event:
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => { const newColorScheme = event.matches ? "dark" : "light"; });
This allows for real-time adjustments in response to user preferences.
The above is the detailed content of How Can I Detect Dark Mode in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!