Home > Web Front-end > CSS Tutorial > How Can I Detect Dark Mode in JavaScript?

How Can I Detect Dark Mode in JavaScript?

Barbara Streisand
Release: 2024-11-11 06:57:03
Original
285 people have browsed it

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 
}
Copy after login

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
}
Copy after login

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";
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template