Media Query Trigger is a tiny JS utility to get notified when a CSS media query becomes active or inactive - useful for bridging two forms of reactivity - media queries and reactive JS frameworks.
npm install mq-trigger
document.addEventListener('mqChange', evt => {
const status = evt.detail.matches ? 'matches' : 'fails to match';
console.log(
);
});
mqTrigger();
`
Example 2: Listen for a particular CSS variable to be updated by media queries as they match or fail to match.
HTML:
`
`
CSS:
`
@media (max-width: 700px) {
p { --foo: 1; }
}
@media (min-width: 701px) and (max-width: 800px) {
p { --foo: 2; }
}
@media (min-width: 801px) {
p { --foo: 3; }
}
`
JS:
`
const p = document.querySelector('p');
p.addEventListener('mqChange', evt =>
p.textContent = evt.detail.styles.getPropertyValue('--foo')
);
`
Usage
Install MQT via NPM or Yarn:
`
npm install mq-trigger
#or
yarn mq-trigger
`
Import via:
`
import { mqTrigger } from 'mq-trigger'
`
MQT is then used by first binding an mqChange event to an element, and then calling mqTrigger(element, filter, stylesheet). All arguments are optional, and work as follows:
- element (element reference) - the element to scope MQT to. If omitted, this will be document. Useful when working with components in reactive frameworks.
- filter (array) - an array of strings with which to filter media queries, e.g. ["700px"] will consider only media queries whose constraint(s) mention "700px". Only matching media queries will be considered. Useful where the DOM contains a great many CSS sheets and it may impact performance to apply MQT to all of them.
- stylesheet (stylesheet object) - a specific stylesheet object for MQT to use, rather than iterating over all the stylesheets under document.stylesheets. Again, useful if the DOM contains many attached stylesheets.
The event will fire once on page load (for initial setup) and then again whenever relevant media queries change state.
The event callback is passed an event object, which contains a sub-object, detail, containing:
- query (string) - the constraint text of the media query whose status changed
- matches (bool) - the media query's status - true if currently matches, false if it doesn't
- styles (obj) - a live CSSStyleDeclaration object of CSS properties (including variables) present on element. These can be retrieved via getPropertyValue().
Use with reactive JS
MQT can be particularly useful when used with a reactive JavaScript framework such as Vue. This is because it can bridge between the reactivity of the framework and the reactivity of media queries.
Consider a Vue component that uses a carousel child component (example). The number of carousel slides visible at any one time is controlled by a prop passed to the carousel, :items-to-show, which we'll bind to a component ref, itemsToShow.
We want our carousel to be responsive, and so as the screen width changes, we want to change this number.
`
``