Detect System Theme Desire Change Utilizing JavaScript


JavaScript and CSS permit customers to detect the consumer theme desire with CSS’ prefers-color-scheme media question. It is commonplace as of late to make use of that desire to indicate the darkish or mild theme on a given web site. However what if the consumer modifications their desire whereas utilizing your app?

To detect a system theme desire change utilizing JavaScript, you might want to mix matchMedia, prefers-color-scheme, and an occasion listener:

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

The change occasion of the matchMedia API notifies you when the system desire modifications. You should use this occasion to mechanically replace the location’s show in actual time.

I like that this API permits detecting consumer desire on a system stage. Catering to consumer wants is a crucial a part of creating a terrific internet expertise!

  • I’m an Impostor

    That is the toughest factor I’ve ever needed to write, a lot much less admit to myself.  I’ve written resignation letters from jobs I’ve liked, I’ve ended relationships, I’ve failed at a number of duties, and let myself down in my life.  All of these emotions had been very…

  • CSS @supports

    Function detection through JavaScript is a shopper aspect finest follow and for all the best causes, however sadly that very same performance hasn’t been accessible inside CSS.  What we find yourself doing is repeating the identical properties a number of instances with every browser prefix.  Yuck.  One other factor we…


Leave a Reply