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
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

  • By
    5 More HTML5 APIs You Didn’t Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

Incredible Demos

  • By
    Introducing MooTools HeatMap

    It's often interesting to think about where on a given element, whether it be the page, an image, or a static DIV, your users are clicking.  With that curiosity in mind, I've created HeatMap: a MooTools class that allows you to detect, load, save, and...

  • By
    Multiple File Upload Input

    More often than not, I find myself wanting to upload more than one file at a time.  Having to use multiple "file" INPUT elements is annoying, slow, and inefficient.  And if I hate them, I can't imagine how annoyed my users would be.  Luckily Safari, Chrome...

Discussion

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