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

How Can I Detect Dark Mode in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 06:57:03245browse

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!

Statement:
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