Last active
January 10, 2017 19:27
-
-
Save VitorLuizC/78ee354fad202950dd3c3b56ec06fe8d to your computer and use it in GitHub Desktop.
Simple module to watch media queries in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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