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

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

Incredible Demos

Discussion

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