Skip to content

Instantly share code, notes, and snippets.

@ryanve
Last active June 9, 2024 21:49
Show Gist options
  • Save ryanve/7924792 to your computer and use it in GitHub Desktop.
Save ryanve/7924792 to your computer and use it in GitHub Desktop.
JavaScript: Get the current media query breakpoint for a CSS feature.
(function(root, name, make) {
if (typeof module != 'undefined' && module['exports']) module['exports'] = make();
else root[name] = make();
}(this, 'breakpoint', function() {
/**
* @link http://gist.github.com/ryanve/7924792
* @param {string} feature range feature name e.g. "width"
* @param {string=} unit CSS unit for feature e.g. "em"
* @param {number=} init initial guess
* @param {number=} step size for iterations
* @return {number} media query breakpoint (0 if none)
*/
function breakpoint(feature, unit, init, step) {
var up, gte, lte, curr, mq = breakpoint['mq'];
unit = typeof unit == 'string' ? unit : '';
init = 0 < init ? (unit ? +init : init>>0) : 1;
// Step starts positive. Minimize iterations, unless feat may be "integer" type.
step = 0 < step ? +step : 0 > step ? -step : 'px' == unit ? 256 : unit ? 32 : 1;
for (feature += ':', unit += ')', curr = init; step && 0 <= curr; curr+=step) {
lte = mq('(min-' + feature + curr + unit);
gte = mq('(max-' + feature + curr + unit);
// Found: Use the floored value if it makes an exact match. Else return as is.
if (lte && gte) return mq('(' + feature + (curr>>0) + unit) ? curr>>0 : curr;
// 1st iteration: Save direction. Flip if down. Break if neither b/c unknown.
if (null == up) step = (up = !gte) ? lte && step : -step;
// Later iterations: If skipped, reverse direction and raise precision.
else if (gte ? up : !up) up = !up, step = -step/2;
}
return 0;
}
var win = window, media = 'matchMedia';
breakpoint['mq'] = win[media] || win[media = 'msMatchMedia'] ? function(q) {
return !!win[media](q).matches;
} : function() {
return false;
};
return breakpoint;
}));
@ryanve
Copy link
Author

ryanve commented Dec 12, 2013

Works for range features and applicable units.

breakpoint('width', 'em') // => 87.40625
breakpoint('device-width', 'px') // => 1440
breakpoint('resolution', 'dpi') // => 96
breakpoint('color') // => 10

@ryanve
Copy link
Author

ryanve commented Feb 6, 2014

I made this into ryanve/actual

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment