Create a gist now

Instantly share code, notes, and snippets.

media query check - matchMedia - moved to
* 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
* in Chrome since m10:
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'); = 'mq-test-1'; = "position:absolute;top:-100em";
return function(q){
div.innerHTML = '_<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth == 42;
return { matches: bool, media: q };
// 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

Eivind Uggedal has apparently fixed a bug with IE8 on this.
I haven't yet confirmed this issue.


And scott reports is the last version to successfully work in IE..


And scott fixed it all! Style elem needs the type attribute!


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


And now I've pulled in nicholas' techniques from 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