mediaquery
Check CSS media queries from script and react when they start or stop
matching, via window.matchMedia. Includes shortcuts for the dark-mode and
reduced-motion user preferences.
Import: @rtorcato/browser-common/mediaquery
๐ MDN: Window.matchMedia() ยท ๐ caniuse: matchmedia
Browser supportโ
| API | Chrome | Edge | Firefox | Safari | iOS Safari | Baseline |
|---|---|---|---|---|---|---|
Window.matchMedia | โ 9+ | โ 12+ | โ 6+ | โ 5.1+ | โ 5+ | Widely available |
โ
supported ยท โ partial ยท โ not supported ยท [n] see note. Generated from MDN browser-compat-data and web-features. caniuse: Window.matchMedia
Exampleโ
import {
matchesMedia,
onMediaQueryChange,
prefersReducedMotion,
} from '@rtorcato/browser-common/mediaquery'
setWide(matchesMedia('(min-width: 768px)') ?? false)
const off = onMediaQueryChange('(min-width: 768px)', (matches) => setWide(matches))
// later:
off()
if (!prefersReducedMotion()) playIntroAnimation()
Exportsโ
isMediaQueryAvailable()โ feature checkmatchesMedia(query)โtrue/false, ornullwhere unsupportedonMediaQueryChange(query, callback)โ subscribe to changes; the callback gets the newmatchesvalue; returns an unsubscribe functionprefersDarkMode()โ(prefers-color-scheme: dark);true/false, ornullwhere unsupportedprefersReducedMotion()โ(prefers-reduced-motion: reduce);true/false, ornullwhere unsupported
See the API reference for full signatures.