1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00
Files
til/javascript/check-media-queries-from-javascript.md

1.2 KiB

Check Media Queries From JavaScript

I'm usually thinking about and using media queries from a CSS context. I use them to control what styles are displayed for a variety of scenarios, such as at different screen widths, when a user prefers reduced motion, or when the user prefers a dark color scheme.

The current value of various media queries can be checked from a JavaScript context as well.

For instance, if we want to see if the user prefers a dark color schema, we can look for a match on that media query with matchMedia.

> window.matchMedia('(prefers-color-scheme: dark)')
MediaQueryList {media: '(prefers-color-scheme: dark)', matches: true, onchange: null}
> window.matchMedia('(prefers-color-scheme: dark)')['matches']
true

This queries for the prefers-color-scheme media feature.

The Astro.build Blog Tutorial shows an example of using this to wire up a Light/Dark mode toggle.