MQS is a very simple event wrapper for the window.matchMedia api, it allows you to add listeners to media queries/breakpoints so that you can execute functions based on them, it's very similar to the resize event listener but more performant.

This page has been created mainly for demo purposes, if you want to know more of how it works you can go to the documentation page in github.


Open your console, keep an eye on it as well as in the first box below, I want you to resize the window horizontally from 360px to +1000px multiple times.

You are in

Notice the change of state and the console logs that appear, also see how the console logs stop appearing depending on the sensor you remove when clicking a yellow button. You can also realize that when you click "Get Active Sensors" it console logs an object with all the active sensors and their properties.

Important Note: For this demo we're using react because EnmaScript is based on it but you can use MQS with raw javascript or the framework/library of your preference.

Adding the sensors

We have 3 functions and each of them is executed in a given breakpoint, these are the functions.

mobileHandler = () => {
        text: 'Mobile',
        color: '#F23C50'

tabletHandler = () => {
        text: 'Tablet',
        color: '#FFCB05'

desktopHandler = () => {
        text: 'Desktop',
        color: '#4AD9D9'

Now we use MQS to bind the functions to the corresponding breakpoints when the component mounts:

    ref: 'mobileSensor',
    mediaQuery: '(max-width: 767px)',
    action: this.mobileHandler

    ref: 'tabletSensor',
    mediaQuery: '(min-width: 768px) and (max-width: 990px)',
    action: this.tabletHandler

    ref: 'desktopSensor',
    mediaQuery: '(min-width: 991px)',
    action: this.desktopHandler

Removing the sensors

To remove the sensors we're adding 4 buttons that use two functions, the first one removes sensors individually by making use of the function MQS.remove():

removeSensor = sensorRef => () => MQS.remove(sensorRef);

We bind this function to the buttons like:

<button onClick={this.removeSensor('mobileSensor')}>
    Remove mobile sensor

<button onClick={this.removeSensor('tabletSensor')}>
    Remove tablet sensor

    Remove desktop sensor

The second one removes all the sensors at once and we bind it to the onClick event directly:

<button onClick={MQS.empty}>Remove All</button>

Getting active sensors

To get all the active sensors we're simply calling the function MQS.get() and console logging it when clicking on a button.

getActiveSensors = () => console.log(MQS.get());

<button onClick={this.getActiveSensors}>
    Get Active Sensors

That's basically it, play around and Have fun.

© Copyright EnmaScript 2020-2021. All code based on the MIT license.