π₯π 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.
npm install media-query-observerShips as CommonJS and an ES module, with TypeScript typings for both.
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';| 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.
Resumes listening for changes. Calling it while already observing does nothing.
Stops listening for changes. Calling it while stopped does nothing.
![]() IE / Edge |
![]() Firefox |
![]() Chrome |
![]() Safari |
![]() Opera |
|---|---|---|---|---|
| IE11, Edge 15+ | 6+ | 36+ | 8+ | 23+ |
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.
MIT




