JavaScript

Detecting dark mode preference using JavaScript

Advertisements

As dark themes have become popular across the web and across operating systems, we might want to check the user’s operating system preference when they visit our website. This way, we can initialize our website accordingly after detecting their dark mode preference.

We can make use of the prefers-color-scheme media feature to help us do this.

Using CSS

@media (prefers-color-scheme: dark) {
  /* styles */
}
CSS

The possible values of the prefers-color-scheme are: light, dark, and no-preference.

Using JavaScript

We will again make use of the same property, but use the window.matchMedia function to check for it.

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

We can then use this to set the default value for a user that has set the dark mode as their operating system default. And we leave the default as light mode for the rest of the users.

If we want to add a listener to the property to ensure that we change the theme as the user switches between the two (this would rarely be a scenario, though), we can do so by:

window
  .matchMedia("(prefers-color-scheme: dark)")
  .addEventListener("change", event => {
    if (event.matches) {
      //dark mode
    } else {
      //light mode
    }
})
JavaScript

And that is it for this super small API! Now, go dark mode everything! 😉

Saransh Kataria

Born in Delhi, India, Saransh Kataria is the brain behind Wisdom Geek. Currently, Saransh is a software developer at a reputed firm in Austin, and he likes playing with new technologies to explore different possibilities. He holds an engineering degree in Computer Science. He also shares his passion for sharing knowledge as the community lead at Facebook Developer Circle Delhi, NCR which is a developer community in Delhi, India.

Share
Published by
Saransh Kataria

Recent Posts

How To Get The Hash of A File In Node.js

While working on a project, I wanted to do an integrity check of a file…

3 days ago

Native popover API in HTML

Popovers have been a problem that was typically solved by using a third-party solution. But…

1 week ago

Node.js 20.6 adds built-in support for .env files

Node.js 20.6 added built-in support for the .env file. This is an excellent addition to the platform…

3 weeks ago

Object destructuring in TypeScript

Object destructuring is a powerful ES 6 feature that can help developers write cleaner code.…

1 month ago

Improve git clone performance in a CI pipeline

Have you felt particularly annoyed by the time it takes to clone a large repository,…

1 month ago

Fix: Hydration failed because the initial UI does not match what was rendered on the server

Within a React or Next.js app, if you encounter the error "Hydration failed because the…

2 months ago
Advertisements