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
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • By
    How to Create a Twitter Card

    One of my favorite social APIs was the Open Graph API adopted by Facebook.  Adding just a few META tags to each page allowed links to my article to be styled and presented the way I wanted them to, giving me a bit of control...

Incredible Demos

Discussion

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