javascript

Check if dark mode is enabled using Javascript

In this post, we can learn how to check if dark mode is enabled on the system or not using javascript code.

const dark_mode_enabled = () =>
    window.matchMedia &&
    window.matchMedia("(prefers-color-scheme: dark)").matches;

console.log(dark_mode_enabled());

Output

true

Live Demo

The above Javascript code will return true if the dark mode theme is enabled on the system and returns false if dark mode is not enabled. You can apply your CSS and JS code after that to make your application open in dark mode.

If you want to put it into a condition then you can use the below code.

if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    // Do something here...
}

If you want to detect the changes when the user is changing the theme mode then you can apply event listener on that.

window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
    if (event.matches) {
        console.log("DARK MODE IS ENABLED");
    } else {
        console.log("LIGHT MODE IS ENABLED");
    }
});

The below code returns true if dark mode is enabled.

window.matchMedia('(prefers-color-scheme: dark)').matches
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    document.getElementsByTagName("body")[0].classList.add("dark");
}
Here we are adding a class that has a name dark to the body tag of our web page.
Was this helpful?