Detect System Theme Desire Change Utilizing JavaScript

[ad_1]

JavaScript and CSS permit customers to detect the consumer theme choice with CSS’ prefers-color-scheme media question. It is normal nowadays to make use of that choice to indicate the darkish or mild 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, it’s good 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 choice modifications. You should utilize this occasion to robotically 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 an ideal internet expertise!


[ad_2]

Leave a Reply

Your email address will not be published. Required fields are marked *