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
    39 Shirts – Leaving Mozilla

    In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...

  • 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...

Incredible Demos

Discussion

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