Created — forked from scottjehl/media query check - media.matchMedium.js

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

media query check - matchMedia - moved to https://github.com/paulirish/matchMedia.js

View matchMedia.js
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
/*
* matchMedia() polyfill - test whether a CSS media type or media query applies
* authors: Scott Jehl, Paul Irish, Nicholas Zakas
* Copyright (c) 2010 Filament Group, Inc
* MIT license
* dev.w3.org/csswg/cssom-view/#dom-window-matchmedia
* in Chrome since m10: http://trac.webkit.org/changeset/72552
*/
 
 
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.appendChild(div);
return function(q){
div.innerHTML = '_<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
div.removeChild(div.firstChild);
bool = div.offsetWidth == 42;
docElem.removeChild(fakeBody);
return { matches: bool, media: q };
};
})(document);
 
 
 
/*
* EXAMPLE USAGE
*/
 
// test 'tv' media type
if (matchMedia('tv').matches) {
// tv media type supported
}
 
// test a mobile device media query
if (matchMedia('only screen and (max-width: 480px)').matches) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
}
 
// test landscape orientation
if (matchMedia('all and (orientation:landscape)').matches) {
// probably tablet in widescreen view
}
 
Owner

Eivind Uggedal has apparently fixed a bug with IE8 on this. https://gist.github.com/747277
I haven't yet confirmed this issue.

Owner

And scott reports https://gist.github.com/710855/8649f3df8f151624500782e4d6915194d2560c5e is the last version to successfully work in IE..

Owner

And scott fixed it all! Style elem needs the type attribute! https://gist.github.com/786768/

Owner

Updated things here.. most notably

  • fixed the return value
  • removed caching (caching isnt very responsive)

I'd still like to pull some ideas from nicholas https://gist.github.com/08602e7d2ee448be834c

Owner

And now I've pulled in nicholas' techniques from https://gist.github.com/08602e7d2ee448be834c Mucho better!

Tested in Chrome, FF3.6, IE6 so far.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.