Detect System Theme Choice Change Utilizing JavaScript

0
3

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

To detect a system theme choice change utilizing JavaScript, you must 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 gentle mode!")
  }
})

The change occasion of the matchMedia API notifies you when the system choice modifications. You need to use this occasion to routinely replace the positioning’s show in actual time.

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


LEAVE A REPLY

Please enter your comment!
Please enter your name here