1.1.0 • Published 5 years ago

libj-query-media v1.1.0

Weekly downloads
3
License
ISC
Repository
-
Last release
5 years ago

libj-query-media

Part of libj tools

This is used to help checking and getting callbacks for media query changes in browser just like css.

Usage (npm)

npm install libj-query-media

run this code and resize browser's window and see console

import { queryMedia } from 'libj-query-media'
queryMedia.run('(max-width: 800px)', true, isMatch => {
    console.log(`max-width ${(isMatch ? 'is' : 'is NOT')} 800px`)
})

Test

  • Run this in a separate command line to start node server
node server.js
  • Run one of the following to re-create bundles
npm run dev
npm run dev:watch

Build

npm run build
npm run build:watch

Make sure to test everything in all browsers (specially IE 10/11)

Source

class QueryMedia {
    /**
     * @param {string} query
     * @param {boolean} callOnChange
     * @event callback : function (isMatch: boolean)
     */
    run(query, callOnChange, callback) {
        var x = window.matchMedia(query);
        var call = function () {
            callback(x.matches);
        };
        if (callOnChange) {
            x.addListener(call);
        }
        call();
    }
    runSync(query = '(max-width: 769px)') {
        var res = false;
        this.run(query, false, isMatch => {
            res = isMatch;
        });
        return res;
    }
}
var queryMedia = new QueryMedia();
export { queryMedia }