mediaq

Listen to media query updates in JavaScript

Install

npm i mediaq
Or
yarn add mediaq

Use

import { Mediaq } from "mediaq";

const mediaq = Mediaq({
    onUpdate: (e) => console.log(e.name, e.media, e.matches),
    mediaQueries: [{
            name: "mobile",
            media: "only screen and (max-width: 600px)"
        }, 
        {
            name: "desktop",
            media: "only screen and (min-width: 600px)"
        },
    ]
});

mediaq.start();

// When done listening 
mediaq.stop();

API

The Mediaq function expects a single object argument with onUpdate and mediaQueries keys.


It returns an object having the start and stop methods.


Demo


How does it work?

The browser exposes the window.matchMedia method. It takes a media query as an argument and returns a MediaQueryList object. This object has the matches boolean property. It also has an event listener that triggers when the media query's match status changes. Here's a list of compatible browsers.