From 55b2c4388308a45afb82710dbac02fdcf19a3633 Mon Sep 17 00:00:00 2001 From: Zander Martineau Date: Wed, 13 Jan 2016 16:35:56 +0000 Subject: [PATCH] add matchMedia shim --- readme.md | 3 ++- shims/matchMedia.js | 46 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 shims/matchMedia.js diff --git a/readme.md b/readme.md index 8103a28..5889571 100644 --- a/readme.md +++ b/readme.md @@ -20,6 +20,7 @@ Create a JavaScript shim set using node. - **EventListener** (EventListener polyfill – [Jonathan Neal](https://github.com/jonathantneal/EventListener)) - **Document.getElementsByClassName** (getElementsByClassName polyfill – [SitePoint](http://www.sitepoint.com/5-useful-functions-missing-in-javascript/)) - **String.trim** (`String.prototype.trim()` – [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) +- **matchMedia** (`matchMedia()` – [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia)) ### Install: @@ -38,7 +39,7 @@ shimly.list(); //lists available shims ```js // ... var shimly = require('shimly') - + shimly.shim(['Array.every', 'Array.forEach'], false, 'shims.js'); // ... ``` diff --git a/shims/matchMedia.js b/shims/matchMedia.js new file mode 100644 index 0000000..7076876 --- /dev/null +++ b/shims/matchMedia.js @@ -0,0 +1,46 @@ +/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license */ + +window.matchMedia || (window.matchMedia = function() { + "use strict"; + + // For browsers that support matchMedium api such as IE 9 and webkit + var styleMedia = (window.styleMedia || window.media); + + // For those that don't support matchMedium + if (!styleMedia) { + var style = document.createElement('style'), + script = document.getElementsByTagName('script')[0], + info = null; + + style.type = 'text/css'; + style.id = 'matchmediajs-test'; + + script.parentNode.insertBefore(style, script); + + // 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers + info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle; + + styleMedia = { + matchMedium: function(media) { + var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }'; + + // 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers + if (style.styleSheet) { + style.styleSheet.cssText = text; + } else { + style.textContent = text; + } + + // Test if media query is true or false + return info.width === '1px'; + } + }; + } + + return function(media) { + return { + matches: styleMedia.matchMedium(media || 'all'), + media: media || 'all' + }; + }; +}()); \ No newline at end of file