Detect Dark Mode Preference with JavaScript

By  on  

Seemingly every website, dapp, and app offers a dark mode preference, and thank goodness. Dark mode is especially useful when I'm doing late night coding, or even worse, trading into altcoins. I'm presently working on implementing a dark theme on MetaMask and it got me to thinking: is there a way we can default to dark mode if the user's operating system also defaults to dark mode?

You can determine if the user's operating system prefers dark mode with one quick line of code:

const prefersDarkMode = window.matchMedia("(prefers-color-scheme:dark)").matches; // true

This code snippet takes advantage of the CSS prefers-color-scheme media query with JavaScript's matchMedia API.

From a user experience standpoint, you'll need to be careful in using this snippet. This method is great for setting a default for new users without changing the value for existing users.

Recent Features

  • By
    Interview with a Pornhub Web Developer

    Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser's video limits to pushing ads through WebSocket so ad blockers don't detect them, you have...

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

Incredible Demos

  • By
    background-size Matters

    It's something that makes all men live in fear, and are often uncertain of. It's never spoken, but the curiosity is always there. Nine out of ten women agree in the affirmative. Advertisers do their best to make us feel inadequate but...

  • By
    Element Position Swapping Using MooTools 1.2

    We all know that MooTools 1.2 can do some pretty awesome animations. What if we want to quickly make two element swap positions without a lot of fuss? Now you can by implementing a MooTools swap() method. MooTools 1.2 Implementation MooTools 1.2 Usage To call the swap...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!