Detect System Theme Preference Change Using JavaScript
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!
Contents
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…
Create a Dynamic Table of Contents Using MooTools 1.2
You’ve probably noticed that I shy away from writing really long articles. Here are a few reasons why: Most site visitors are coming from Google and just want a straight to the point, bail-me-out ASAP answer to a question. I’ve noticed that I have a hard time…
Create a Brilliant Sprited, CSS-Powered Firefox Animation
Mozilla recently formally announced Firefox OS and its partners at Mobile World Congress and I couldn’t be more excited. Firefox OS is going to change the lives of people in developing countries, hopefully making a name for itself in the US as well. The…
[ad_2]
Source link