Skip to main content

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โ€‹

APIChromeEdgeFirefoxSafariiOS SafariBaseline
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 check
  • matchesMedia(query) โ€” true / false, or null where unsupported
  • onMediaQueryChange(query, callback) โ€” subscribe to changes; the callback gets the new matches value; returns an unsubscribe function
  • prefersDarkMode() โ€” (prefers-color-scheme: dark); true / false, or null where unsupported
  • prefersReducedMotion() โ€” (prefers-reduced-motion: reduce); true / false, or null where unsupported

See the API reference for full signatures.