/

How to Detect Dark Mode Using JavaScript

How to Detect Dark Mode Using JavaScript

Detecting dark mode and mode changes using JavaScript

CSS provides a way to detect dark mode using the prefers-color-scheme media query. But what if we need to use JavaScript? I recently encountered this problem when I had JavaScript code that needed to show a different image based on the light or dark mode.

Here’s how we can approach it:

  1. First, we need to check if the matchMedia object exists to determine if the browser supports dark mode. If it doesn’t, we can fall back to light mode.

  2. To check if it’s dark mode, we can use the following code:

    1
    window.matchMedia('(prefers-color-scheme: dark)').matches

    This code will return true if dark mode is enabled.

  3. Let’s consider a full example where we invert the colors of an image if it’s dark mode:

    1
    2
    3
    4
    const img = document.querySelector('#myimage');
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    img.style.filter = "invert(100%)";
    }

    In this example, the img variable represents the image element, and by applying the CSS filter property with the invert function, we invert the colors.

However, we need to handle a potential issue. What if the user changes the mode while using our website? To address this, we can detect the mode change using an event listener:

1
2
3
4
5
6
7
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (event) => {
if (event.matches) {
// dark mode
} else {
// light mode
}
});

In the code snippet above, we listen for changes to the preferred color scheme using the change event and determine the mode based on the matches property of the event.

Tags: dark mode, JavaScript, CSS, prefers-color-scheme, image, event listener