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
    CSS vs. JS Animation: Which is Faster?

    How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps? This article serves as a point-by-point...

  • By
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

Incredible Demos

  • By
    Adding Events to Adding Events in MooTools

    Note: This post has been updated. One of my huge web peeves is when an element has click events attached to it but the element doesn't sport the "pointer" cursor. I mean how the hell is the user supposed to know they can/should click on...

  • By
    spellcheck Attribute

    Many useful attributes have been provided to web developers recently:  download, placeholder, autofocus, and more.  One helpful older attribute is the spellcheck attribute which allows developers to  control an elements ability to be spell checked or subject to grammar checks.  Simple enough, right?

Discussion

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