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();
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
pnpm add mediaq
yarn add mediaq
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.