public
Last active

modernizr media query testing and hair pulling

  • Download Gist
matchMedia version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
window.matchMedia = window.matchMedia || (function(doc, undefined){
 
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement('body'),
div = doc.createElement('div');
 
div.id = 'mq-test-1';
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
 
return function(q){
 
div.innerHTML = '&shy;<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
 
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth == 42;
docElem.removeChild(fakeBody);
 
return { matches: bool, media: q };
};
 
})(document);
modernizr version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
testMediaQuery = function( mq ) {
 
var matchMedia = window.matchMedia || window.msMatchMedia;
if ( matchMedia ) {
return matchMedia(mq).matches;
}
 
var bool;
 
injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) {
bool = (window.getComputedStyle ?
getComputedStyle(node, null) :
node.currentStyle)['position'] == 'absolute';
});
 
return bool;
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.