Detect System Theme Preference Change Using JavaScript

By  on  

JavaScript and CSS allow users to detect the user theme preference with CSS' prefers-color-scheme media query. It's standard these days to use that preference to show the dark or light theme on a given website. But what if the user changes their preference while using your app?

To detect a system theme preference change using JavaScript, you need to combine matchMedia, prefers-color-scheme, and an event listener:

window.matchMedia('(prefers-color-scheme: dark)')
      .addEventListener('change',({ matches }) => {
  if (matches) {
    console.log("change to dark mode!")
  } else {
    console.log("change to light mode!")
  }
})

The change event of the matchMedia API notifies you when the system preference changes. You can use this event to automatically update the site's display in real time.

I love that this API allows detecting user preference on a system level. Catering to user needs is an important part of creating a great web experience!

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
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

Incredible Demos

  • By
    CSS Columns

    One major gripe that we've always had about CSS is that creating layouts seems to be more difficult than it should be. We have, of course, adapted and mastered the techniques for creating layouts, but there's no shaking the feeling that there should be a...

  • By
    Use Custom Missing Image Graphics Using Dojo

    A few months back I posted an article about how you can use your own "missing image" graphics when an image fails to load using MooTools and jQuery. Here's how to do the same using Dojo. The HTML We'll delegate the image to display by class...

Discussion

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