Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
(function () {
var
documentElement = document.documentElement,
viewportFontSize, viewportHeight, viewportIsPortrait, viewportMax, viewportMin, viewportWidth;
function getViewportFontSize() {
var
body = documentElement.appendChild(document.createElement('body')),
iframe = document.createElement('iframe'),
iframeDocument;
iframe.style.cssText = 'clip:rect(0 0 0 0);position:absolute';
body.appendChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.write('<div style=height:1em;overflow:hidden>');
iframeDocument.close();
viewportFontSize = iframeDocument.body.lastChild.clientHeight;
documentElement.removeChild(body);
}
function getViewportSize() {
viewportHeight = Math.max(documentElement.clientHeight, documentElement.offsetHeight);
viewportWidth = Math.max(documentElement.clientWidth, documentElement.offsetWidth);
viewportMax = Math.max(viewportHeight, viewportWidth);
viewportMin = Math.min(viewportHeight, viewportWidth);
viewportIsPortrait = viewportHeight > viewportWidth;
}
function replace() {
var args = arguments, index = 0, string = args[0];
while (++index in args) {
string = string.replace(args[index], args[++index]);
}
return string;
}
function computeCSSValue(length, unit) {
return length * replace(unit,
/cm/, 37.7952,
/r?em/, viewportFontSize,
/in/, 96,
/mm/, 3.77952,
/pc/, 16,
/pt/, 4 / 3,
/px/, 1,
/vh/, viewportHeight,
/vmax/, viewportMax,
/vmin/, viewportMin,
/vw/, viewportWidth
);
}
function evaluateMediaQuery(query) {
return new Function('e', 'try{return ' + replace(String(query || 1).toLowerCase(),
// ignore `only`
/^only\s+/g, '',
// wrap `not`
/not([^)]+)/g, '!($1)',
// interpret `all`, `portrait`, and `screen` as truthy
/all|portrait|screen/g, 1,
// interpret `landscape`, `print` and `speech` as falsey
/landscape|print|speech/g, 0,
// interpret `and`
/\band\b/g, '&&',
// interpret `,`
/,/g, '||',
// interpret `min-` as >=
/min-([a-z-\s]+):/g, 'e.$1>=',
// interpret `min-` as <=
/max-([a-z-\s]+):/g, 'e.$1<=',
// interpret others as ==
/([a-z-\s]+):/g, 'e.$1==',
// calc for calc not for mq ;-)
/calc([^)]+)/g, '($1)',
// interpret css values
/(\d+)([a-z]+)/g, function (match, length, unit) {
return computeCSSValue(length, unit);
}
// make eval safer?!?
,/^(?!(e.width|e.height|e.orienation|[0-9\.&=|><\+\-\*\(\)\/])).*/ig, ''
) + '}catch(e){}')({
height: viewportHeight,
orientation: viewportIsPortrait,
width: viewportWidth
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.