Software

Detect System Theme Preference Change Using JavaScript

[ad_1]

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!

  • Responsive Images: The Ultimate Guide

    Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today’s websites and devices become ever more varied, a plethora of responsive images…

  • Write Better JavaScript with Promises

    You’ve probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don’t see what makes them so special. Can’t you just use a callback? What’s the big deal? In this article, we’ll…


[ad_2]
Source link
Show More

admin

Makes Noise is a blog where you can find all the juicy details on a variety of topics including health and fitness, technology, lifestyle, entertainment, love and relationships, beauty and makeup, sports and so much more. The blog is updated regularly to make sure you have all the latest and greatest information on the topics that matter most to you.

Related Articles

Leave a Reply

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

Back to top button