Home > Article > Web Front-end > How to Detect Dark Mode in JavaScript?
With the widespread adoption of dark mode in operating systems like Windows and macOS, developers need a way to adapt their web applications accordingly. This task arises when customizing user interfaces and styling elements dynamically based on the system's preferred color scheme.
One approach involves using CSS media queries to target dark mode preferences. However, when handling elements styled in JavaScript, such as those created using the Stripe Elements API, a more comprehensive solution is required.
To determine the operating system's color scheme programmatically in JavaScript, utilize the following technique:
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { // Dark mode is active }
This method checks if the browser supports the window.matchMedia() API and then employs a media query to verify if the system's preferred color scheme is dark.
To monitor changes in color scheme preference, use the following code:
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => { const newColorScheme = event.matches ? "dark" : "light"; });
This listener function monitors any modifications in the media query and provides an event object that indicates the new color scheme. Developers can then update their applications dynamically to match the current system settings.
By implementing this technique, web applications can seamlessly adapt to dark mode, providing users with a consistent and visually appealing experience across different systems and operating conditions.
The above is the detailed content of How to Detect Dark Mode in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!