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!
Create a CSS Cube
CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals. Add animation and you’ve got something really neat. Unfortunately each CSS cube tutorial I’ve read is a bit…
CSS Tooltips
We all know that you can make shapes with CSS and a single HTML element, as I’ve covered in my CSS Triangles and CSS Circles posts. Triangles and circles are fairly simply though, so as CSS advances, we need to stretch the boundaries…