Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

big refactor to incorporate nicholas's technique.

  • Loading branch information...
commit 50c64c88521a3a378a1432ebf8cac1bf7083dbb4 1 parent cc40a9b
@paulirish authored
Showing with 24 additions and 33 deletions.
  1. +24 −33 matchMedia.js
View
57 matchMedia.js
@@ -1,6 +1,6 @@
/*
* matchMedia() polyfill - test whether a CSS media type or media query applies
-* authors: Scott Jehl, Paul Irish
+* authors: Scott Jehl, Paul Irish, Nicholas Zakas
* Copyright (c) 2010 Filament Group, Inc
* MIT license
@@ -10,42 +10,33 @@
* To check media type, just do: matchMedia('tv')
*/
-if (!window.matchMedia){
+
+window.matchMedia = window.matchMedia || (function(doc, undefined){
- window.matchMedia = (function(doc, undefined){
-
- var bool,
- docElem = doc.documentElement,
- fakeBody = doc.createElement('body'),
- testDiv = doc.createElement('div');
+ 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){
- testDiv.setAttribute('id','ejs-qtest');
- fakeBody.appendChild(testDiv);
+ div.innerHTML = '_<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
- return function(q){
-
- var styleBlock = doc.createElement('style'),
- cssrule = '@media '+q+' { #ejs-qtest { position: absolute; } }';
-
- styleBlock.type = "text/css"; //must set type for IE!
- if (styleBlock.styleSheet){
- styleBlock.styleSheet.cssText = cssrule;
- }
- else {
- styleBlock.appendChild(doc.createTextNode(cssrule));
- }
- docElem.insertBefore(fakeBody, docElem.firstChild);
- docElem.insertBefore(styleBlock, docElem.firstChild);
- bool = ((window.getComputedStyle ? window.getComputedStyle(testDiv,null) : testDiv.currentStyle)['position'] == 'absolute');
- docElem.removeChild(fakeBody);
- docElem.removeChild(styleBlock);
-
- return { matches: bool, media: q };
- };
+ docElem.insertBefore(fakeBody, refNode);
+ div.removeChild(div.firstChild);
+ bool = div.offsetWidth == 42;
+ docElem.removeChild(fakeBody);
- })(document);
-
-}
+ return { matches: bool, media: q };
+ };
+
+})(document);
Please sign in to comment.
Something went wrong with that request. Please try again.