mediaq

Track media query changes in JavaScript.

Make your JavaScript aware of media queries with mediaq, so it can respond to changes in layout, device capabilities, and user preferences.

import { mediaq } from "mediaq";

const listener = mediaq({
  mediaQueries: [
    { name: "desktop", media: "(min-width: 768px)" },
    { name: "dark", media: "(prefers-color-scheme: dark)" },
  ],
  onUpdate: (state) => {
    console.log(state.matches);
  },
});

listener.start();
Copy

Live queries

A live demo of a few media queries in your browser.

0 8 media queries are matching

Install

Install mediaq with the package manager of your choice.

npm install mediaq
Copy
pnpm add mediaq
Copy
yarn add mediaq
Copy

API

mediaq exposes a small runtime API.

mediaq

Create a listener from a set of media queries and an update callback.

start()

Method on the object returned by mediaq that begins listening to the media queries you pass in.

stop()

Method on the object returned by mediaq that stops listening for future media query updates.

isListening()

Method on the object returned by mediaq that checks whether the listener is currently active.