Skip to content

About

πŸ–₯πŸ‘€ Run a callback when a CSS media query starts or stops matching

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

media-query-observer

Node.js CI Coverage Status npm

πŸ–₯πŸ‘€ Run a callback when a CSS media query starts or stops matching.

A small wrapper over window.matchMedia that calls onMatch / onUnmatch for the current state at once and again on every change, and falls back to the legacy addListener / removeListener API in browsers that lack addEventListener on MediaQueryList.

Install

npm install media-query-observer

Ships as CommonJS and an ES module, with TypeScript typings for both.

Usage

import MediaQueryObserver from 'media-query-observer';

const observer = new MediaQueryObserver({
  mediaQuery: '(max-width: 1024px)',
  onMatch: ({ firstTime }) => console.log('matches', { firstTime }),
  onUnmatch: () => console.log('does not match'),
});

// later
observer.stopObserving();
observer.startObserving();

In TypeScript the option and callback types are exported too:

import MediaQueryObserver, { type MediaQueryObserverOptions, type OnMatchParams } from 'media-query-observer';

API

new MediaQueryObserver({ mediaQuery, onMatch, onUnmatch })

Option Type Description
mediaQuery string The media query to observe. A non-string throws a TypeError.
onMatch ({ firstTime: boolean }) => void Optional. Called when the query matches. firstTime is true on the first call only.
onUnmatch () => void Optional. Called when the query does not match.

The constructor calls the callback for the current state right away and starts observing.

startObserving()

Resumes listening for changes. Calling it while already observing does nothing.

stopObserving()

Stops listening for changes. Calling it while stopped does nothing.

Browsers support

IE / Edge
IE / Edge
Firefox
Firefox
Chrome
Chrome
Safari
Safari
Opera
Opera
IE11, Edge 15+ 6+ 36+ 8+ 23+

Development

Node.js is only needed to build and test; the version is pinned in .nvmrc.

npm install
npm run lint           # oxlint + tsc type check
npm test               # or test:watch, test:coverage
npm run build          # lint + test + build β†’ dist/

Pushing a v* tag publishes to npm from CI.

License

MIT

About

πŸ–₯πŸ‘€ Run a callback when a CSS media query starts or stops matching

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages