Sign In

js-mq-match

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
Package was removed
Sorry, it seems this package was removed from the registry

js-mq-match

A simple wrapper over window.matchMedia API

unpublished
latest
Source
npmnpm
Version
1.0.3
Version published
Maintainers
1
Created
Source

JS MQ match

JS MQ Match is a simple package that leverages window.matchMedia API. It provides a wrapper on top of this API. This wrapper is a static class, that allows subscribing / unsubscribing from a media query.

How to consume it

In order to consume this simple package, you first need to install it:

npm i js-mq-match

After you installed it in your app, wherever you need to listen to media queries you just call the subscribe method of the static class.

import { MediaQueryListener } from 'js-mq-match';

// Handler that receives a boolean representing if the media query matches
const handler = (matches) => {
    console.log('Query matches ', matches);
}
const query = '(max-width: 768px)';

MediaQueryListener.subscribe(handler, query);

// When you no longer need to listen (important to call this at some point 
// so that the listener is removed when there are no more subscribers listening to this query)
MediaQueryListener.unsubscribe(handler, query);

How it works

Being a global static class, whenever you subscribe from somewhere within the code to a specific query, it checks if there is already a subscription to the query:

  • if there is not, it will add the callback as the first subscriber to the query, and add a change event listener for that query, which will call all of the subscribed callbacks on changes.
  • if there is, it will just push the callback to the list of subscribers for that query.

It will also call the callback with the initial value (before change events happen).

When unsubscribe method is called, it removes the callback from the subscription list for that query, and if it reaches a point where there are no more subscribed callbacks, it will remove the event listener created in the initial subscribe call for that query.

Keywords

matchMedia

FAQs

Package last updated on 02 Dec 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts