Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Last active January 10, 2017 19:27
Show Gist options
  • Save VitorLuizC/78ee354fad202950dd3c3b56ec06fe8d to your computer and use it in GitHub Desktop.
Save VitorLuizC/78ee354fad202950dd3c3b56ec06fe8d to your computer and use it in GitHub Desktop.
Simple module to watch media queries in JavaScript
const points = {
print: 'print',
xs: 'screen',
sm: '48rem',
md: '64rem',
lg: '75rem'
};
/**
* Launch callback when breakpoint start/stop working.
* @param {string|any} point
* @param {function} callback
*/
function watch(point, callback) {
var media = window.matchMedia(createPoint(point));
media.addListener(handler);
handler();
function handler() {
if (media.matches)
callback(true);
else
callback(false);
}
}
/**
* Check if value is a CSS length.
* @param {string} value
* @returns {boolean}
*/
function isCSSLength(value) {
var length = /^(\+|-)?([0-9]*\.)?[0-9]+(em|ex|ch|rem|vh|vw|vmin|vmax|px|mm|cm|in|pt|pc|%)$/i;
var zero = /^(\+|-)?(0*\.)?0+$/;
return length.test(value) || zero.test(value);
}
/**
* Create a simple media query.
* @param {string|any} point
* @param {string} [maxMin]
* @returns {string}
*/
function createPoint(point, maxMin = "min") {
if (typeof point !== 'string') {
point = String(point);
}
return isCSSLength(point) ? `(${maxMin}-width: ${point})` : point;
}
export default { points, watch, createPoint };
import breakpoint from "./breakpoint";
breakpoint.watch(breakpoint.points.md, higher => higher
? console.log('> 64rem')
: console.log('<= 64rem')
);
breakpoint.watch(breakpoint.createPoint('768px', 'max'), lower => lower
? console.log('<= 768px')
: console.log('> 768px')
);
breakpoint.watch(breakpoint.createPoint('print'), onPrint => onPrint
? console.log('Print')
: console.log('Not on print')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment