Skip to content

Instantly share code, notes, and snippets.

@deepfriedmind
Last active August 29, 2015 14:03
Show Gist options
  • Save deepfriedmind/2d9cd38fcf97cbacc1a7 to your computer and use it in GitHub Desktop.
Save deepfriedmind/2d9cd38fcf97cbacc1a7 to your computer and use it in GitHub Desktop.
Media Query Matcher. Match a specific breakpoint using Modernizr.mq() (example breakpoints are Bootstrap defaults) – Requires Modernizr, obviously.
class MediaQueries
breakpoints =
screenXS: '(min-width: 480px)'
screenXSmax: '(max-width: 767px)'
screenSM: '(min-width: 768px)'
screenMD: '(min-width: 992px)'
screenLG: '(min-width: 1200px)'
errorMsg = 'Invalid or no breakpoint specified.'
if Object.keys? then errorMsg += " Valid arguments: #{Object.keys(breakpoints)}"
###*
* Match a specific breakpoint using Modernizr.mq()
* @param {string} breakpoint Any key from {Object} breakpoints
* @return {boolean} true if query matches against the current state of the window
###
match: (breakpoint) =>
if not breakpoint? or not breakpoints.hasOwnProperty(breakpoint) then throw new Error errorMsg
Modernizr.mq breakpoints[breakpoint]
constructor: ->
if not Modernizr?.mq? then @match = -> throw new Error 'Modernizr is not initialized.'
# Usage:
mq = new MediaQueries()
mq.match 'screenLG' # `true` or `false`
var MediaQueries, mq,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
MediaQueries = (function() {
var breakpoints, errorMsg;
breakpoints = {
screenXS: '(min-width: 480px)',
screenXSmax: '(max-width: 767px)',
screenSM: '(min-width: 768px)',
screenMD: '(min-width: 992px)',
screenLG: '(min-width: 1200px)'
};
errorMsg = 'Invalid or no breakpoint specified.';
if (Object.keys != null) {
errorMsg += " Valid arguments: " + (Object.keys(breakpoints));
}
/**
* Match a specific breakpoint using Modernizr.mq()
* @param {string} breakpoint Any key from {Object} breakpoints
* @return {boolean} true if query matches against the current state of the window
*/
MediaQueries.prototype.match = function(breakpoint) {
if ((breakpoint == null) || !breakpoints.hasOwnProperty(breakpoint)) {
throw new Error(errorMsg);
}
return Modernizr.mq(breakpoints[breakpoint]);
};
function MediaQueries() {
this.match = __bind(this.match, this);
if ((typeof Modernizr !== "undefined" && Modernizr !== null ? Modernizr.mq : void 0) == null) {
this.match = function() {
throw new Error('Modernizr is not initialized.');
};
}
}
return MediaQueries;
})();
// Usage:
mq = new MediaQueries();
mq.match('screenLG'); // `true` or `false`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment