├── .gitignore ├── Gruntfile.js ├── LICENSE-MIT ├── README.md ├── bower.json ├── cross-domain ├── example-base.html ├── example.html ├── respond-proxy.html ├── respond.proxy.gif └── respond.proxy.js ├── dest ├── respond.matchmedia.addListener.min.js ├── respond.matchmedia.addListener.src.js ├── respond.min.js └── respond.src.js ├── package.json ├── src ├── matchmedia.addListener.js ├── matchmedia.polyfill.js └── respond.js └── test ├── test.css ├── test.html ├── test2.css └── unit ├── index.html ├── qunit ├── qunit.css └── qunit.js ├── test-with-comment.css ├── test-with-dpr.css ├── test-with-keyframe.css ├── test.css ├── test2.css ├── test3.css └── tests.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .vimdir 3 | node_modules 4 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | module.exports = function(grunt) { 2 | "use strict"; 3 | 4 | // Project configuration. 5 | grunt.initConfig({ 6 | pkg: grunt.file.readJSON('package.json'), 7 | banner: 8 | '/*! Respond.js v<%= pkg.version %>: <%= pkg.description %>\n' + 9 | ' * Copyright <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>\n' + 10 | ' * Licensed under <%= _.pluck(pkg.licenses, "type").join(", ") %>\n' + 11 | ' * <%= pkg.homepageShortened %>' + 12 | ' */\n\n', 13 | uglify: { 14 | nonMinMatchMedia: { 15 | options: { 16 | banner: '<%= banner %>', 17 | mangle: false, 18 | compress: false, 19 | preserveComments: 'some', 20 | beautify: { 21 | beautify: true, 22 | indent_level: 2 23 | } 24 | }, 25 | files: { 26 | 'dest/respond.src.js': ['src/matchmedia.polyfill.js', 'src/respond.js'] 27 | } 28 | }, 29 | minMatchMedia: { 30 | options: { 31 | banner: '<%= banner %>' 32 | }, 33 | files: { 34 | 'dest/respond.min.js': ['src/matchmedia.polyfill.js', 'src/respond.js'] 35 | } 36 | }, 37 | nonMinMatchMediaListener: { 38 | options: { 39 | banner: '<%= banner %>', 40 | mangle: false, 41 | compress: false, 42 | preserveComments: 'some', 43 | beautify: { 44 | beautify: true, 45 | indent_level: 2 46 | } 47 | }, 48 | files: { 49 | 'dest/respond.matchmedia.addListener.src.js': ['src/matchmedia.polyfill.js', 'src/matchmedia.addListener.js', 'src/respond.js'] 50 | } 51 | }, 52 | minMatchMediaListener: { 53 | options: { 54 | banner: '<%= banner %>' 55 | }, 56 | files: { 57 | 'dest/respond.matchmedia.addListener.min.js': ['src/matchmedia.polyfill.js', 'src/matchmedia.addListener.js', 'src/respond.js'] 58 | } 59 | } 60 | }, 61 | jshint: { 62 | files: ['src/respond.js', 'src/matchmedia.polyfill.js'], 63 | options: { 64 | curly: true, 65 | eqeqeq: true, 66 | immed: true, 67 | latedef: false, 68 | newcap: true, 69 | noarg: true, 70 | sub: true, 71 | undef: true, 72 | boss: true, 73 | eqnull: true, 74 | smarttabs: true, 75 | node: true, 76 | es5: true, 77 | strict: false 78 | }, 79 | globals: { 80 | Image: true, 81 | window: true 82 | } 83 | } 84 | }); 85 | 86 | grunt.loadNpmTasks( 'grunt-contrib-jshint' ); 87 | grunt.loadNpmTasks( 'grunt-contrib-uglify' ); 88 | 89 | // Default task. 90 | grunt.registerTask('default', ['jshint', 'uglify']); 91 | 92 | }; 93 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 Scott Jehl 2 | 3 | Permission is hereby granted, free of charge, to any person 4 | obtaining a copy of this software and associated documentation 5 | files (the "Software"), to deal in the Software without 6 | restriction, including without limitation the rights to use, 7 | copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the 9 | Software is furnished to do so, subject to the following 10 | conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 17 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 19 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 20 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 21 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Respond.js 2 | ### A fast & lightweight polyfill for min/max-width CSS3 Media Queries (for IE 6-8, and more) 3 | 4 | - Copyright 2011: Scott Jehl, scottjehl.com 5 | 6 | - Licensed under the MIT license. 7 | 8 | The goal of this script is to provide a fast and lightweight (3kb minified / 1kb gzipped) script to enable [responsive web designs](http://www.alistapart.com/articles/responsive-web-design/) in browsers that don't support CSS3 Media Queries - in particular, Internet Explorer 8 and under. It's written in such a way that it will probably patch support for other non-supporting browsers as well (more information on that soon). 9 | 10 | If you're unfamiliar with the concepts surrounding Responsive Web Design, you can read up [here](http://www.alistapart.com/articles/responsive-web-design/) and also [here](https://scottjehl.github.io/picturefill/) 11 | 12 | [Demo page](https://scottjehl.github.io/Respond/test/test.html) (the colors change to show media queries working) 13 | 14 | 15 | Usage Instructions 16 | ====== 17 | 18 | 1. Craft your CSS with min/max-width media queries to adapt your layout from mobile (first) all the way up to desktop 19 | ```css 20 | @media screen and (min-width: 480px){ 21 | /** ...styles for 480px and up go here **/ 22 | } 23 | ``` 24 | 25 | 2. Reference the respond.min.js script (1kb min/gzipped) after all of your CSS (the earlier it runs, the greater chance IE users will not see a flash of un-media'd content) 26 | 27 | 3. Crack open Internet Explorer and pump fists in delight 28 | 29 | 30 | CDN/X-Domain Setup 31 | ====== 32 | 33 | Respond.js works by requesting a pristine copy of your CSS via AJAX, so if you host your stylesheets on a CDN (or a subdomain), you'll need to set up a local proxy to request the CSS for old IE browsers. Prior versions recommended a deprecated x-domain approach, but a local proxy is preferable (for performance and security reasons) to attempting to work around the cross-domain limitations. 34 | 35 | 36 | Support & Caveats 37 | ====== 38 | 39 | Some notes to keep in mind: 40 | 41 | - This script's focus is purposely very narrow: only min-width and max-width media queries and all media types (screen, print, etc) are translated to non-supporting browsers. I wanted to keep things simple for filesize, maintenance, and performance, so I've intentionally limited support to queries that are essential to building a (mobile-first) responsive design. In the future, I may rework things a bit to include a hook for patching-in additional media query features - stay tuned! 42 | 43 | - Browsers that natively support CSS3 Media Queries are opted-out of running this script as quickly as possible. In testing for support, all other browsers are subjected to a quick test to determine whether they support media queries or not before proceeding to run the script. This test is now included separately at the top, and uses the window.matchMedia polyfill found here: https://github.com/paulirish/matchMedia.js . If you are already including this polyfill via Modernizr or otherwise, feel free to remove that part. 44 | 45 | - This script relies on no other scripts or frameworks (aside from the included matchMedia polyfill), and is optimized for mobile delivery (~1kb total filesize min/gzip) 46 | 47 | - As you might guess, this implementation is quite dumb in regards to CSS parsing rules. This is a good thing, because that allows it to run really fast, but its looseness may also cause unexpected behavior. For example: if you enclose a whole media query in a comment intending to disable its rules, you'll probably find that those rules will end up enabled in non-media-query-supporting browsers. 48 | 49 | - Respond.js doesn't parse CSS referenced via @import, nor does it work with media queries within style elements, as those styles can't be re-requested for parsing. 50 | 51 | - Due to security restrictions, some browsers may not allow this script to work on file:// urls (because it uses xmlHttpRequest). Run it on a web server. 52 | 53 | - If the request for the CSS file that includes MQ-specific styling is 54 | behind a redirect, Respond.js will fail silently. CSS files should 55 | respond with a 200 status. 56 | 57 | - Currently, media attributes on link elements are supported, but only if the linked stylesheet contains no media queries. If it does contain queries, the media attribute will be ignored and the internal queries will be parsed normally. In other words, @media statements in the CSS take priority. 58 | 59 | - Reportedly, if CSS files are encoded in UTF-8 with Byte-Order-Mark (BOM), they will not work with Respond.js in IE7 or IE8. Noted in issue #97 60 | 61 | - WARNING: Including @font-face rules inside a media query will cause IE7 and IE8 to hang during load. To work around this, place @font-face rules in the wide open, as a sibling to other media queries. 62 | 63 | - If you have more than 32 stylesheets referenced, IE will throw an error, `Invalid procedure call or argument`. Concatenate your CSS and the issue should go away. 64 | 65 | - Sass/SCSS source maps are not supported; `@media -sass-debug-info` will break respond.js. Noted in issue [#148](https://github.com/scottjehl/Respond/issues/148) 66 | 67 | - Internet Explorer 9 supports css3 media queries, but not within frames when the CSS containing the media query is in an external file (this appears to be a bug in IE9 — see https://stackoverflow.com/questions/10316247/media-queries-fail-inside-ie9-iframe). See this commit for a fix if you're having this problem. https://github.com/NewSignature/Respond/commit/1c86c66075f0a2099451eb426702fc3540d2e603 68 | 69 | - Nested Media Queries are not supported 70 | 71 | 72 | How's it work? 73 | ====== 74 | Basically, the script loops through the CSS referenced in the page and runs a regular expression or two on their contents to find media queries and their associated blocks of CSS. In Internet Explorer, the content of the stylesheet is impossible to retrieve in its pre-parsed state (which in IE 8-, means its media queries are removed from the text), so Respond.js re-requests the CSS files using Ajax and parses the text response from there. Be sure to configure your CSS files' caching properly so that this re-request doesn't actually go to the server, hitting your browser cache instead. 75 | 76 | From there, each media query block is appended to the head in order via style elements, and those style elements are enabled and disabled (read: appended and removed from the DOM) depending on how their min/max width compares with the browser width. The media attribute on the style elements will match that of the query in the CSS, so it could be "screen", "projector", or whatever you want. Any relative paths contained in the CSS will be prefixed by their stylesheet's href, so image paths will direct to their proper destination 77 | 78 | API Options? 79 | ====== 80 | Sure, a couple: 81 | 82 | - respond.update() : rerun the parser (helpful if you added a stylesheet to the page and it needs to be translated) 83 | - respond.mediaQueriesSupported: set to true if the browser natively supports media queries. 84 | - respond.getEmValue() : returns the pixel value of one em 85 | 86 | 87 | Alternatives to this script 88 | ====== 89 | This isn't the only CSS3 Media Query polyfill script out there; but it damn well may be the fastest. 90 | 91 | If you're looking for more robust CSS3 Media Query support, you might check out https://code.google.com/p/css3-mediaqueries-js/. In testing, I've found that script to be noticeably slow when rendering complex responsive designs (both in filesize and performance), but it really does support a lot more media query features than this script. Big hat tip to the authors! :) 92 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "respond", 3 | "version": "1.4.2", 4 | "main": "dest/respond.src.js", 5 | "description": "Fast and lightweight polyfill for min/max-width CSS3 Media Queries (for IE 6-8, and more)", 6 | "ignore": [ 7 | "**/.*", 8 | "test" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /cross-domain/example-base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Respond JS Test Page 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |

This is a visual test file for cross-domain proxy and custom base tag. NB: For this test to work properly, you need to set the href attribute of the base tag to the fully-qualified path to cross-domain on your system, terminated with a slash (earlier versions of IE don't play nicely otherwise).

19 | 20 |

The media queries in the included CSS file simply change the body's background color depending on the browser width. If you see any colors aside from black, then the media queries are working in your browser. You can resize your browser window to see it change on the fly.

21 | 22 | 23 |

Media-attributes are working too! This should be visible above 600px.

24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /cross-domain/example.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Respond JS Test Page 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |

This is a visual test file for cross-domain proxy.

17 | 18 |

The media queries in the included CSS file simply change the body's background color depending on the browser width. If you see any colors aside from black, then the media queries are working in your browser. You can resize your browser window to see it change on the fly.

19 | 20 | 21 |

Media-attributes are working too! This should be visible above 600px.

22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /cross-domain/respond-proxy.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Respond JS Proxy 7 | 8 | 9 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /cross-domain/respond.proxy.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/scottjehl/Respond/9d91fd47eb59c11a80d570d4ea0beaa59cfc71bf/cross-domain/respond.proxy.gif -------------------------------------------------------------------------------- /cross-domain/respond.proxy.js: -------------------------------------------------------------------------------- 1 | /*! Respond.js: min/max-width media query polyfill. Remote proxy (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */ 2 | (function(win, doc, undefined){ 3 | var docElem = doc.documentElement, 4 | proxyURL = doc.getElementById("respond-proxy").href, 5 | redirectURL = (doc.getElementById("respond-redirect") || location).href, 6 | baseElem = doc.getElementsByTagName("base")[0], 7 | urls = [], 8 | refNode; 9 | 10 | function encode(url){ 11 | return win.encodeURIComponent(url); 12 | } 13 | 14 | function fakejax( url, callback ){ 15 | 16 | var iframe, 17 | AXO; 18 | 19 | // All hail Google https://j.mp/iKMI19 20 | // Behold, an iframe proxy without annoying clicky noises. 21 | if ( "ActiveXObject" in win ) { 22 | AXO = new ActiveXObject( "htmlfile" ); 23 | AXO.open(); 24 | AXO.write( '' ); 25 | AXO.close(); 26 | iframe = AXO.getElementById( "x" ); 27 | } else { 28 | iframe = doc.createElement( "iframe" ); 29 | iframe.style.cssText = "position:absolute;top:-99em"; 30 | docElem.insertBefore(iframe, docElem.firstElementChild || docElem.firstChild ); 31 | } 32 | 33 | iframe.src = checkBaseURL(proxyURL) + "?url=" + encode(redirectURL) + "&css=" + encode(checkBaseURL(url)); 34 | 35 | function checkFrameName() { 36 | var cssText; 37 | 38 | try { 39 | cssText = iframe.contentWindow.name; 40 | } 41 | catch (e) { } 42 | 43 | if (cssText) { 44 | // We've got what we need. Stop the iframe from loading further content. 45 | iframe.src = "about:blank"; 46 | iframe.parentNode.removeChild(iframe); 47 | iframe = null; 48 | 49 | 50 | // Per https://j.mp/kn9EPh, not taking any chances. Flushing the ActiveXObject 51 | if (AXO) { 52 | AXO = null; 53 | 54 | if (win.CollectGarbage) { 55 | win.CollectGarbage(); 56 | } 57 | } 58 | 59 | callback(cssText); 60 | } 61 | else{ 62 | win.setTimeout(checkFrameName, 100); 63 | } 64 | } 65 | 66 | win.setTimeout(checkFrameName, 500); 67 | } 68 | 69 | // https://stackoverflow.com/a/472729 70 | function checkBaseURL(href) { 71 | var el = document.createElement('div'), 72 | escapedURL = href.split('&').join('&'). 73 | split('<').join('<'). 74 | split('"').join('"'); 75 | 76 | el.innerHTML = 'x'; 77 | return el.firstChild.href; 78 | } 79 | 80 | function checkRedirectURL() { 81 | // IE6 & IE7 don't build out absolute urls in attributes. 82 | // So respond.proxy.gif remains relative instead of https://example.com/respond.proxy.gif. 83 | // This trickery resolves that issue. 84 | if (~ !redirectURL.indexOf(location.host)) { 85 | 86 | var fakeLink = doc.createElement("div"); 87 | 88 | fakeLink.innerHTML = ''; 89 | docElem.insertBefore(fakeLink, docElem.firstElementChild || docElem.firstChild ); 90 | 91 | // Grab the parsed URL from that dummy object 92 | redirectURL = fakeLink.firstChild.href; 93 | 94 | // Clean up 95 | fakeLink.parentNode.removeChild(fakeLink); 96 | fakeLink = null; 97 | } 98 | } 99 | 100 | function buildUrls(){ 101 | var links = doc.getElementsByTagName( "link" ); 102 | 103 | for( var i = 0, linkl = links.length; i < linkl; i++ ){ 104 | 105 | var thislink = links[i], 106 | href = links[i].href, 107 | extreg = (/^([a-zA-Z:]*\/\/(www\.)?)/).test( href ), 108 | ext = (baseElem && !extreg) || extreg; 109 | 110 | //make sure it's an external stylesheet 111 | if( thislink.rel.indexOf( "stylesheet" ) >= 0 && ext ){ 112 | (function( link ){ 113 | fakejax( href, function( css ){ 114 | link.styleSheet.rawCssText = css; 115 | respond.update(); 116 | } ); 117 | })( thislink ); 118 | } 119 | } 120 | 121 | 122 | } 123 | 124 | if( !respond.mediaQueriesSupported ){ 125 | checkRedirectURL(); 126 | buildUrls(); 127 | } 128 | 129 | })( window, document ); 130 | -------------------------------------------------------------------------------- /dest/respond.matchmedia.addListener.min.js: -------------------------------------------------------------------------------- 1 | /*! Respond.js v1.4.2: min/max-width media query polyfill 2 | * Copyright 2014 Scott Jehl 3 | * Licensed under MIT 4 | * https://j.mp/respondjs */ 5 | 6 | !function(a){"use strict";a.matchMedia=a.matchMedia||function(a){var b,c=a.documentElement,d=c.firstElementChild||c.firstChild,e=a.createElement("body"),f=a.createElement("div");return f.id="mq-test-1",f.style.cssText="position:absolute;top:-100em",e.style.background="none",e.appendChild(f),function(a){return f.innerHTML='­',c.insertBefore(e,d),b=42===f.offsetWidth,c.removeChild(e),{matches:b,media:a}}}(a.document)}(this),function(a){"use strict";if(a.matchMedia&&a.matchMedia("all").addListener)return!1;var b=a.matchMedia,c=b("only all").matches,d=!1,e=0,f=[],g=function(){a.clearTimeout(e),e=a.setTimeout(function(){for(var c=0,d=f.length;d>c;c++){var e=f[c].mql,g=f[c].listeners||[],h=b(e.media).matches;if(h!==e.matches){e.matches=h;for(var i=0,j=g.length;j>i;i++)g[i].call(a,e)}}},30)};a.matchMedia=function(e){var h=b(e),i=[],j=0;return h.addListener=function(b){c&&(d||(d=!0,a.addEventListener("resize",g,!0)),0===j&&(j=f.push({mql:h,listeners:i})),i.push(b))},h.removeListener=function(a){for(var b=0,c=i.length;c>b;b++)i[b]===a&&i.splice(b,1)},h}}(this),function(a){"use strict";function b(){v(!0)}var c={};a.respond=c,c.update=function(){};var d=[],e=function(){var b=!1;try{b=new a.XMLHttpRequest}catch(c){b=new a.ActiveXObject("Microsoft.XMLHTTP")}return function(){return b}}(),f=function(a,b){var c=e();c&&(c.open("GET",a,!0),c.onreadystatechange=function(){4!==c.readyState||200!==c.status&&304!==c.status||b(c.responseText)},4!==c.readyState&&c.send(null))},g=function(a){return a.replace(c.regex.minmaxwh,"").match(c.regex.other)};if(c.ajax=f,c.queue=d,c.unsupportedmq=g,c.regex={media:/@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi,keyframes:/@(?:\-(?:o|moz|webkit)\-)?keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]*\}/gi,comments:/\/\*[^*]*\*+([^/][^*]*\*+)*\//gi,urls:/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,findStyles:/@media *([^\{]+)\{([\S\s]+?)$/,only:/(only\s+)?([a-zA-Z]+)\s?/,minw:/\(\s*min\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/,maxw:/\(\s*max\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/,minmaxwh:/\(\s*m(in|ax)\-(height|width)\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/gi,other:/\([^\)]*\)/g},c.mediaQueriesSupported=a.matchMedia&&null!==a.matchMedia("only all")&&a.matchMedia("only all").matches,!c.mediaQueriesSupported){var h,i,j,k=a.document,l=k.documentElement,m=[],n=[],o=[],p={},q=30,r=k.getElementsByTagName("head")[0]||l,s=k.getElementsByTagName("base")[0],t=r.getElementsByTagName("link"),u=function(){var a,b=k.createElement("div"),c=k.body,d=l.style.fontSize,e=c&&c.style.fontSize,f=!1;return b.style.cssText="position:absolute;font-size:1em;width:1em",c||(c=f=k.createElement("body"),c.style.background="none"),l.style.fontSize="100%",c.style.fontSize="100%",c.appendChild(b),f&&l.insertBefore(c,l.firstChild),a=b.offsetWidth,f?l.removeChild(c):c.removeChild(b),l.style.fontSize=d,e&&(c.style.fontSize=e),a=j=parseFloat(a)},v=function(b){var c="clientWidth",d=l[c],e="CSS1Compat"===k.compatMode&&d||k.body[c]||d,f={},g=t[t.length-1],p=(new Date).getTime();if(b&&h&&q>p-h)return a.clearTimeout(i),i=a.setTimeout(v,q),void 0;h=p;for(var s in m)if(m.hasOwnProperty(s)){var w=m[s],x=w.minw,y=w.maxw,z=null===x,A=null===y,B="em";x&&(x=parseFloat(x)*(x.indexOf(B)>-1?j||u():1)),y&&(y=parseFloat(y)*(y.indexOf(B)>-1?j||u():1)),w.hasquery&&(z&&A||!(z||e>=x)||!(A||y>=e))||(f[w.media]||(f[w.media]=[]),f[w.media].push(n[w.rules]))}for(var C in o)o.hasOwnProperty(C)&&o[C]&&o[C].parentNode===r&&r.removeChild(o[C]);o.length=0;for(var D in f)if(f.hasOwnProperty(D)){var E=k.createElement("style"),F=f[D].join("\n");E.type="text/css",E.media=D,r.insertBefore(E,g.nextSibling),E.styleSheet?E.styleSheet.cssText=F:E.appendChild(k.createTextNode(F)),o.push(E)}},w=function(a,b,d){var e=a.replace(c.regex.comments,"").replace(c.regex.keyframes,"").match(c.regex.media),f=e&&e.length||0;b=b.substring(0,b.lastIndexOf("/"));var h=function(a){return a.replace(c.regex.urls,"$1"+b+"$2$3")},i=!f&&d;b.length&&(b+="/"),i&&(f=1);for(var j=0;f>j;j++){var k,l,o,p;i?(k=d,n.push(h(a))):(k=e[j].match(c.regex.findStyles)&&RegExp.$1,n.push(RegExp.$2&&h(RegExp.$2))),o=k.split(","),p=o.length;for(var q=0;p>q;q++)l=o[q],g(l)||m.push({media:l.split("(")[0].match(c.regex.only)&&RegExp.$2||"all",rules:n.length-1,hasquery:l.indexOf("(")>-1,minw:l.match(c.regex.minw)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:l.match(c.regex.maxw)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}v()},x=function(){if(d.length){var b=d.shift();f(b.href,function(c){w(c,b.href,b.media),p[b.href]=!0,a.setTimeout(function(){x()},0)})}},y=function(){for(var b=0;b #mq-test-1 { width: 42px; }'; 18 | docElem.insertBefore(fakeBody, refNode); 19 | bool = div.offsetWidth === 42; 20 | docElem.removeChild(fakeBody); 21 | return { 22 | matches: bool, 23 | media: q 24 | }; 25 | }; 26 | }(w.document); 27 | })(this); 28 | 29 | /*! matchMedia() polyfill addListener/removeListener extension. Author & copyright (c) 2012: Scott Jehl. Dual MIT/BSD license */ 30 | (function(w) { 31 | "use strict"; 32 | if (w.matchMedia && w.matchMedia("all").addListener) { 33 | return false; 34 | } 35 | var localMatchMedia = w.matchMedia, hasMediaQueries = localMatchMedia("only all").matches, isListening = false, timeoutID = 0, queries = [], handleChange = function(evt) { 36 | w.clearTimeout(timeoutID); 37 | timeoutID = w.setTimeout(function() { 38 | for (var i = 0, il = queries.length; i < il; i++) { 39 | var mql = queries[i].mql, listeners = queries[i].listeners || [], matches = localMatchMedia(mql.media).matches; 40 | if (matches !== mql.matches) { 41 | mql.matches = matches; 42 | for (var j = 0, jl = listeners.length; j < jl; j++) { 43 | listeners[j].call(w, mql); 44 | } 45 | } 46 | } 47 | }, 30); 48 | }; 49 | w.matchMedia = function(media) { 50 | var mql = localMatchMedia(media), listeners = [], index = 0; 51 | mql.addListener = function(listener) { 52 | if (!hasMediaQueries) { 53 | return; 54 | } 55 | if (!isListening) { 56 | isListening = true; 57 | w.addEventListener("resize", handleChange, true); 58 | } 59 | if (index === 0) { 60 | index = queries.push({ 61 | mql: mql, 62 | listeners: listeners 63 | }); 64 | } 65 | listeners.push(listener); 66 | }; 67 | mql.removeListener = function(listener) { 68 | for (var i = 0, il = listeners.length; i < il; i++) { 69 | if (listeners[i] === listener) { 70 | listeners.splice(i, 1); 71 | } 72 | } 73 | }; 74 | return mql; 75 | }; 76 | })(this); 77 | 78 | (function(w) { 79 | "use strict"; 80 | var respond = {}; 81 | w.respond = respond; 82 | respond.update = function() {}; 83 | var requestQueue = [], xmlHttp = function() { 84 | var xmlhttpmethod = false; 85 | try { 86 | xmlhttpmethod = new w.XMLHttpRequest(); 87 | } catch (e) { 88 | xmlhttpmethod = new w.ActiveXObject("Microsoft.XMLHTTP"); 89 | } 90 | return function() { 91 | return xmlhttpmethod; 92 | }; 93 | }(), ajax = function(url, callback) { 94 | var req = xmlHttp(); 95 | if (!req) { 96 | return; 97 | } 98 | req.open("GET", url, true); 99 | req.onreadystatechange = function() { 100 | if (req.readyState !== 4 || req.status !== 200 && req.status !== 304) { 101 | return; 102 | } 103 | callback(req.responseText); 104 | }; 105 | if (req.readyState === 4) { 106 | return; 107 | } 108 | req.send(null); 109 | }, isUnsupportedMediaQuery = function(query) { 110 | return query.replace(respond.regex.minmaxwh, "").match(respond.regex.other); 111 | }; 112 | respond.ajax = ajax; 113 | respond.queue = requestQueue; 114 | respond.unsupportedmq = isUnsupportedMediaQuery; 115 | respond.regex = { 116 | media: /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi, 117 | keyframes: /@(?:\-(?:o|moz|webkit)\-)?keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]*\}/gi, 118 | comments: /\/\*[^*]*\*+([^/][^*]*\*+)*\//gi, 119 | urls: /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, 120 | findStyles: /@media *([^\{]+)\{([\S\s]+?)$/, 121 | only: /(only\s+)?([a-zA-Z]+)\s?/, 122 | minw: /\(\s*min\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/, 123 | maxw: /\(\s*max\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/, 124 | minmaxwh: /\(\s*m(in|ax)\-(height|width)\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/gi, 125 | other: /\([^\)]*\)/g 126 | }; 127 | respond.mediaQueriesSupported = w.matchMedia && w.matchMedia("only all") !== null && w.matchMedia("only all").matches; 128 | if (respond.mediaQueriesSupported) { 129 | return; 130 | } 131 | var doc = w.document, docElem = doc.documentElement, mediastyles = [], rules = [], appendedEls = [], parsedSheets = {}, resizeThrottle = 30, head = doc.getElementsByTagName("head")[0] || docElem, base = doc.getElementsByTagName("base")[0], links = head.getElementsByTagName("link"), lastCall, resizeDefer, eminpx, getEmValue = function() { 132 | var ret, div = doc.createElement("div"), body = doc.body, originalHTMLFontSize = docElem.style.fontSize, originalBodyFontSize = body && body.style.fontSize, fakeUsed = false; 133 | div.style.cssText = "position:absolute;font-size:1em;width:1em"; 134 | if (!body) { 135 | body = fakeUsed = doc.createElement("body"); 136 | body.style.background = "none"; 137 | } 138 | docElem.style.fontSize = "100%"; 139 | body.style.fontSize = "100%"; 140 | body.appendChild(div); 141 | if (fakeUsed) { 142 | docElem.insertBefore(body, docElem.firstChild); 143 | } 144 | ret = div.offsetWidth; 145 | if (fakeUsed) { 146 | docElem.removeChild(body); 147 | } else { 148 | body.removeChild(div); 149 | } 150 | docElem.style.fontSize = originalHTMLFontSize; 151 | if (originalBodyFontSize) { 152 | body.style.fontSize = originalBodyFontSize; 153 | } 154 | ret = eminpx = parseFloat(ret); 155 | return ret; 156 | }, applyMedia = function(fromResize) { 157 | var name = "clientWidth", docElemProp = docElem[name], currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[name] || docElemProp, styleBlocks = {}, lastLink = links[links.length - 1], now = new Date().getTime(); 158 | if (fromResize && lastCall && now - lastCall < resizeThrottle) { 159 | w.clearTimeout(resizeDefer); 160 | resizeDefer = w.setTimeout(applyMedia, resizeThrottle); 161 | return; 162 | } else { 163 | lastCall = now; 164 | } 165 | for (var i in mediastyles) { 166 | if (mediastyles.hasOwnProperty(i)) { 167 | var thisstyle = mediastyles[i], min = thisstyle.minw, max = thisstyle.maxw, minnull = min === null, maxnull = max === null, em = "em"; 168 | if (!!min) { 169 | min = parseFloat(min) * (min.indexOf(em) > -1 ? eminpx || getEmValue() : 1); 170 | } 171 | if (!!max) { 172 | max = parseFloat(max) * (max.indexOf(em) > -1 ? eminpx || getEmValue() : 1); 173 | } 174 | if (!thisstyle.hasquery || (!minnull || !maxnull) && (minnull || currWidth >= min) && (maxnull || currWidth <= max)) { 175 | if (!styleBlocks[thisstyle.media]) { 176 | styleBlocks[thisstyle.media] = []; 177 | } 178 | styleBlocks[thisstyle.media].push(rules[thisstyle.rules]); 179 | } 180 | } 181 | } 182 | for (var j in appendedEls) { 183 | if (appendedEls.hasOwnProperty(j)) { 184 | if (appendedEls[j] && appendedEls[j].parentNode === head) { 185 | head.removeChild(appendedEls[j]); 186 | } 187 | } 188 | } 189 | appendedEls.length = 0; 190 | for (var k in styleBlocks) { 191 | if (styleBlocks.hasOwnProperty(k)) { 192 | var ss = doc.createElement("style"), css = styleBlocks[k].join("\n"); 193 | ss.type = "text/css"; 194 | ss.media = k; 195 | head.insertBefore(ss, lastLink.nextSibling); 196 | if (ss.styleSheet) { 197 | ss.styleSheet.cssText = css; 198 | } else { 199 | ss.appendChild(doc.createTextNode(css)); 200 | } 201 | appendedEls.push(ss); 202 | } 203 | } 204 | }, translate = function(styles, href, media) { 205 | var qs = styles.replace(respond.regex.comments, "").replace(respond.regex.keyframes, "").match(respond.regex.media), ql = qs && qs.length || 0; 206 | href = href.substring(0, href.lastIndexOf("/")); 207 | var repUrls = function(css) { 208 | return css.replace(respond.regex.urls, "$1" + href + "$2$3"); 209 | }, useMedia = !ql && media; 210 | if (href.length) { 211 | href += "/"; 212 | } 213 | if (useMedia) { 214 | ql = 1; 215 | } 216 | for (var i = 0; i < ql; i++) { 217 | var fullq, thisq, eachq, eql; 218 | if (useMedia) { 219 | fullq = media; 220 | rules.push(repUrls(styles)); 221 | } else { 222 | fullq = qs[i].match(respond.regex.findStyles) && RegExp.$1; 223 | rules.push(RegExp.$2 && repUrls(RegExp.$2)); 224 | } 225 | eachq = fullq.split(","); 226 | eql = eachq.length; 227 | for (var j = 0; j < eql; j++) { 228 | thisq = eachq[j]; 229 | if (isUnsupportedMediaQuery(thisq)) { 230 | continue; 231 | } 232 | mediastyles.push({ 233 | media: thisq.split("(")[0].match(respond.regex.only) && RegExp.$2 || "all", 234 | rules: rules.length - 1, 235 | hasquery: thisq.indexOf("(") > -1, 236 | minw: thisq.match(respond.regex.minw) && parseFloat(RegExp.$1) + (RegExp.$2 || ""), 237 | maxw: thisq.match(respond.regex.maxw) && parseFloat(RegExp.$1) + (RegExp.$2 || "") 238 | }); 239 | } 240 | } 241 | applyMedia(); 242 | }, makeRequests = function() { 243 | if (requestQueue.length) { 244 | var thisRequest = requestQueue.shift(); 245 | ajax(thisRequest.href, function(styles) { 246 | translate(styles, thisRequest.href, thisRequest.media); 247 | parsedSheets[thisRequest.href] = true; 248 | w.setTimeout(function() { 249 | makeRequests(); 250 | }, 0); 251 | }); 252 | } 253 | }, ripCSS = function() { 254 | for (var i = 0; i < links.length; i++) { 255 | var sheet = links[i], href = sheet.href, media = sheet.media, isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet"; 256 | if (!!href && isCSS && !parsedSheets[href]) { 257 | if (sheet.styleSheet && sheet.styleSheet.rawCssText) { 258 | translate(sheet.styleSheet.rawCssText, href, media); 259 | parsedSheets[href] = true; 260 | } else { 261 | if (!/^([a-zA-Z:]*\/\/)/.test(href) && !base || href.replace(RegExp.$1, "").split("/")[0] === w.location.host) { 262 | if (href.substring(0, 2) === "//") { 263 | href = w.location.protocol + href; 264 | } 265 | requestQueue.push({ 266 | href: href, 267 | media: media 268 | }); 269 | } 270 | } 271 | } 272 | } 273 | makeRequests(); 274 | }; 275 | ripCSS(); 276 | respond.update = ripCSS; 277 | respond.getEmValue = getEmValue; 278 | function callMedia() { 279 | applyMedia(true); 280 | } 281 | if (w.addEventListener) { 282 | w.addEventListener("resize", callMedia, false); 283 | } else if (w.attachEvent) { 284 | w.attachEvent("onresize", callMedia); 285 | } 286 | })(this); 287 | -------------------------------------------------------------------------------- /dest/respond.min.js: -------------------------------------------------------------------------------- 1 | /*! Respond.js v1.4.2: min/max-width media query polyfill 2 | * Copyright 2014 Scott Jehl 3 | * Licensed under MIT 4 | * https://j.mp/respondjs */ 5 | 6 | !function(a){"use strict";a.matchMedia=a.matchMedia||function(a){var b,c=a.documentElement,d=c.firstElementChild||c.firstChild,e=a.createElement("body"),f=a.createElement("div");return f.id="mq-test-1",f.style.cssText="position:absolute;top:-100em",e.style.background="none",e.appendChild(f),function(a){return f.innerHTML='­',c.insertBefore(e,d),b=42===f.offsetWidth,c.removeChild(e),{matches:b,media:a}}}(a.document)}(this),function(a){"use strict";function b(){v(!0)}var c={};a.respond=c,c.update=function(){};var d=[],e=function(){var b=!1;try{b=new a.XMLHttpRequest}catch(c){b=new a.ActiveXObject("Microsoft.XMLHTTP")}return function(){return b}}(),f=function(a,b){var c=e();c&&(c.open("GET",a,!0),c.onreadystatechange=function(){4!==c.readyState||200!==c.status&&304!==c.status||b(c.responseText)},4!==c.readyState&&c.send(null))},g=function(a){return a.replace(c.regex.minmaxwh,"").match(c.regex.other)};if(c.ajax=f,c.queue=d,c.unsupportedmq=g,c.regex={media:/@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi,keyframes:/@(?:\-(?:o|moz|webkit)\-)?keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]*\}/gi,comments:/\/\*[^*]*\*+([^/][^*]*\*+)*\//gi,urls:/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,findStyles:/@media *([^\{]+)\{([\S\s]+?)$/,only:/(only\s+)?([a-zA-Z]+)\s?/,minw:/\(\s*min\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/,maxw:/\(\s*max\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/,minmaxwh:/\(\s*m(in|ax)\-(height|width)\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/gi,other:/\([^\)]*\)/g},c.mediaQueriesSupported=a.matchMedia&&null!==a.matchMedia("only all")&&a.matchMedia("only all").matches,!c.mediaQueriesSupported){var h,i,j,k=a.document,l=k.documentElement,m=[],n=[],o=[],p={},q=30,r=k.getElementsByTagName("head")[0]||l,s=k.getElementsByTagName("base")[0],t=r.getElementsByTagName("link"),u=function(){var a,b=k.createElement("div"),c=k.body,d=l.style.fontSize,e=c&&c.style.fontSize,f=!1;return b.style.cssText="position:absolute;font-size:1em;width:1em",c||(c=f=k.createElement("body"),c.style.background="none"),l.style.fontSize="100%",c.style.fontSize="100%",c.appendChild(b),f&&l.insertBefore(c,l.firstChild),a=b.offsetWidth,f?l.removeChild(c):c.removeChild(b),l.style.fontSize=d,e&&(c.style.fontSize=e),a=j=parseFloat(a)},v=function(b){var c="clientWidth",d=l[c],e="CSS1Compat"===k.compatMode&&d||k.body[c]||d,f={},g=t[t.length-1],p=(new Date).getTime();if(b&&h&&q>p-h)return a.clearTimeout(i),i=a.setTimeout(v,q),void 0;h=p;for(var s in m)if(m.hasOwnProperty(s)){var w=m[s],x=w.minw,y=w.maxw,z=null===x,A=null===y,B="em";x&&(x=parseFloat(x)*(x.indexOf(B)>-1?j||u():1)),y&&(y=parseFloat(y)*(y.indexOf(B)>-1?j||u():1)),w.hasquery&&(z&&A||!(z||e>=x)||!(A||y>=e))||(f[w.media]||(f[w.media]=[]),f[w.media].push(n[w.rules]))}for(var C in o)o.hasOwnProperty(C)&&o[C]&&o[C].parentNode===r&&r.removeChild(o[C]);o.length=0;for(var D in f)if(f.hasOwnProperty(D)){var E=k.createElement("style"),F=f[D].join("\n");E.type="text/css",E.media=D,r.insertBefore(E,g.nextSibling),E.styleSheet?E.styleSheet.cssText=F:E.appendChild(k.createTextNode(F)),o.push(E)}},w=function(a,b,d){var e=a.replace(c.regex.comments,"").replace(c.regex.keyframes,"").match(c.regex.media),f=e&&e.length||0;b=b.substring(0,b.lastIndexOf("/"));var h=function(a){return a.replace(c.regex.urls,"$1"+b+"$2$3")},i=!f&&d;b.length&&(b+="/"),i&&(f=1);for(var j=0;f>j;j++){var k,l,o,p;i?(k=d,n.push(h(a))):(k=e[j].match(c.regex.findStyles)&&RegExp.$1,n.push(RegExp.$2&&h(RegExp.$2))),o=k.split(","),p=o.length;for(var q=0;p>q;q++)l=o[q],g(l)||m.push({media:l.split("(")[0].match(c.regex.only)&&RegExp.$2||"all",rules:n.length-1,hasquery:l.indexOf("(")>-1,minw:l.match(c.regex.minw)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:l.match(c.regex.maxw)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}v()},x=function(){if(d.length){var b=d.shift();f(b.href,function(c){w(c,b.href,b.media),p[b.href]=!0,a.setTimeout(function(){x()},0)})}},y=function(){for(var b=0;b #mq-test-1 { width: 42px; }'; 18 | docElem.insertBefore(fakeBody, refNode); 19 | bool = div.offsetWidth === 42; 20 | docElem.removeChild(fakeBody); 21 | return { 22 | matches: bool, 23 | media: q 24 | }; 25 | }; 26 | }(w.document); 27 | })(this); 28 | 29 | (function(w) { 30 | "use strict"; 31 | var respond = {}; 32 | w.respond = respond; 33 | respond.update = function() {}; 34 | var requestQueue = [], xmlHttp = function() { 35 | var xmlhttpmethod = false; 36 | try { 37 | xmlhttpmethod = new w.XMLHttpRequest(); 38 | } catch (e) { 39 | xmlhttpmethod = new w.ActiveXObject("Microsoft.XMLHTTP"); 40 | } 41 | return function() { 42 | return xmlhttpmethod; 43 | }; 44 | }(), ajax = function(url, callback) { 45 | var req = xmlHttp(); 46 | if (!req) { 47 | return; 48 | } 49 | req.open("GET", url, true); 50 | req.onreadystatechange = function() { 51 | if (req.readyState !== 4 || req.status !== 200 && req.status !== 304) { 52 | return; 53 | } 54 | callback(req.responseText); 55 | }; 56 | if (req.readyState === 4) { 57 | return; 58 | } 59 | req.send(null); 60 | }, isUnsupportedMediaQuery = function(query) { 61 | return query.replace(respond.regex.minmaxwh, "").match(respond.regex.other); 62 | }; 63 | respond.ajax = ajax; 64 | respond.queue = requestQueue; 65 | respond.unsupportedmq = isUnsupportedMediaQuery; 66 | respond.regex = { 67 | media: /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi, 68 | keyframes: /@(?:\-(?:o|moz|webkit)\-)?keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]*\}/gi, 69 | comments: /\/\*[^*]*\*+([^/][^*]*\*+)*\//gi, 70 | urls: /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, 71 | findStyles: /@media *([^\{]+)\{([\S\s]+?)$/, 72 | only: /(only\s+)?([a-zA-Z]+)\s?/, 73 | minw: /\(\s*min\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/, 74 | maxw: /\(\s*max\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/, 75 | minmaxwh: /\(\s*m(in|ax)\-(height|width)\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/gi, 76 | other: /\([^\)]*\)/g 77 | }; 78 | respond.mediaQueriesSupported = w.matchMedia && w.matchMedia("only all") !== null && w.matchMedia("only all").matches; 79 | if (respond.mediaQueriesSupported) { 80 | return; 81 | } 82 | var doc = w.document, docElem = doc.documentElement, mediastyles = [], rules = [], appendedEls = [], parsedSheets = {}, resizeThrottle = 30, head = doc.getElementsByTagName("head")[0] || docElem, base = doc.getElementsByTagName("base")[0], links = head.getElementsByTagName("link"), lastCall, resizeDefer, eminpx, getEmValue = function() { 83 | var ret, div = doc.createElement("div"), body = doc.body, originalHTMLFontSize = docElem.style.fontSize, originalBodyFontSize = body && body.style.fontSize, fakeUsed = false; 84 | div.style.cssText = "position:absolute;font-size:1em;width:1em"; 85 | if (!body) { 86 | body = fakeUsed = doc.createElement("body"); 87 | body.style.background = "none"; 88 | } 89 | docElem.style.fontSize = "100%"; 90 | body.style.fontSize = "100%"; 91 | body.appendChild(div); 92 | if (fakeUsed) { 93 | docElem.insertBefore(body, docElem.firstChild); 94 | } 95 | ret = div.offsetWidth; 96 | if (fakeUsed) { 97 | docElem.removeChild(body); 98 | } else { 99 | body.removeChild(div); 100 | } 101 | docElem.style.fontSize = originalHTMLFontSize; 102 | if (originalBodyFontSize) { 103 | body.style.fontSize = originalBodyFontSize; 104 | } 105 | ret = eminpx = parseFloat(ret); 106 | return ret; 107 | }, applyMedia = function(fromResize) { 108 | var name = "clientWidth", docElemProp = docElem[name], currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[name] || docElemProp, styleBlocks = {}, lastLink = links[links.length - 1], now = new Date().getTime(); 109 | if (fromResize && lastCall && now - lastCall < resizeThrottle) { 110 | w.clearTimeout(resizeDefer); 111 | resizeDefer = w.setTimeout(applyMedia, resizeThrottle); 112 | return; 113 | } else { 114 | lastCall = now; 115 | } 116 | for (var i in mediastyles) { 117 | if (mediastyles.hasOwnProperty(i)) { 118 | var thisstyle = mediastyles[i], min = thisstyle.minw, max = thisstyle.maxw, minnull = min === null, maxnull = max === null, em = "em"; 119 | if (!!min) { 120 | min = parseFloat(min) * (min.indexOf(em) > -1 ? eminpx || getEmValue() : 1); 121 | } 122 | if (!!max) { 123 | max = parseFloat(max) * (max.indexOf(em) > -1 ? eminpx || getEmValue() : 1); 124 | } 125 | if (!thisstyle.hasquery || (!minnull || !maxnull) && (minnull || currWidth >= min) && (maxnull || currWidth <= max)) { 126 | if (!styleBlocks[thisstyle.media]) { 127 | styleBlocks[thisstyle.media] = []; 128 | } 129 | styleBlocks[thisstyle.media].push(rules[thisstyle.rules]); 130 | } 131 | } 132 | } 133 | for (var j in appendedEls) { 134 | if (appendedEls.hasOwnProperty(j)) { 135 | if (appendedEls[j] && appendedEls[j].parentNode === head) { 136 | head.removeChild(appendedEls[j]); 137 | } 138 | } 139 | } 140 | appendedEls.length = 0; 141 | for (var k in styleBlocks) { 142 | if (styleBlocks.hasOwnProperty(k)) { 143 | var ss = doc.createElement("style"), css = styleBlocks[k].join("\n"); 144 | ss.type = "text/css"; 145 | ss.media = k; 146 | head.insertBefore(ss, lastLink.nextSibling); 147 | if (ss.styleSheet) { 148 | ss.styleSheet.cssText = css; 149 | } else { 150 | ss.appendChild(doc.createTextNode(css)); 151 | } 152 | appendedEls.push(ss); 153 | } 154 | } 155 | }, translate = function(styles, href, media) { 156 | var qs = styles.replace(respond.regex.comments, "").replace(respond.regex.keyframes, "").match(respond.regex.media), ql = qs && qs.length || 0; 157 | href = href.substring(0, href.lastIndexOf("/")); 158 | var repUrls = function(css) { 159 | return css.replace(respond.regex.urls, "$1" + href + "$2$3"); 160 | }, useMedia = !ql && media; 161 | if (href.length) { 162 | href += "/"; 163 | } 164 | if (useMedia) { 165 | ql = 1; 166 | } 167 | for (var i = 0; i < ql; i++) { 168 | var fullq, thisq, eachq, eql; 169 | if (useMedia) { 170 | fullq = media; 171 | rules.push(repUrls(styles)); 172 | } else { 173 | fullq = qs[i].match(respond.regex.findStyles) && RegExp.$1; 174 | rules.push(RegExp.$2 && repUrls(RegExp.$2)); 175 | } 176 | eachq = fullq.split(","); 177 | eql = eachq.length; 178 | for (var j = 0; j < eql; j++) { 179 | thisq = eachq[j]; 180 | if (isUnsupportedMediaQuery(thisq)) { 181 | continue; 182 | } 183 | mediastyles.push({ 184 | media: thisq.split("(")[0].match(respond.regex.only) && RegExp.$2 || "all", 185 | rules: rules.length - 1, 186 | hasquery: thisq.indexOf("(") > -1, 187 | minw: thisq.match(respond.regex.minw) && parseFloat(RegExp.$1) + (RegExp.$2 || ""), 188 | maxw: thisq.match(respond.regex.maxw) && parseFloat(RegExp.$1) + (RegExp.$2 || "") 189 | }); 190 | } 191 | } 192 | applyMedia(); 193 | }, makeRequests = function() { 194 | if (requestQueue.length) { 195 | var thisRequest = requestQueue.shift(); 196 | ajax(thisRequest.href, function(styles) { 197 | translate(styles, thisRequest.href, thisRequest.media); 198 | parsedSheets[thisRequest.href] = true; 199 | w.setTimeout(function() { 200 | makeRequests(); 201 | }, 0); 202 | }); 203 | } 204 | }, ripCSS = function() { 205 | for (var i = 0; i < links.length; i++) { 206 | var sheet = links[i], href = sheet.href, media = sheet.media, isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet"; 207 | if (!!href && isCSS && !parsedSheets[href]) { 208 | if (sheet.styleSheet && sheet.styleSheet.rawCssText) { 209 | translate(sheet.styleSheet.rawCssText, href, media); 210 | parsedSheets[href] = true; 211 | } else { 212 | if (!/^([a-zA-Z:]*\/\/)/.test(href) && !base || href.replace(RegExp.$1, "").split("/")[0] === w.location.host) { 213 | if (href.substring(0, 2) === "//") { 214 | href = w.location.protocol + href; 215 | } 216 | requestQueue.push({ 217 | href: href, 218 | media: media 219 | }); 220 | } 221 | } 222 | } 223 | } 224 | makeRequests(); 225 | }; 226 | ripCSS(); 227 | respond.update = ripCSS; 228 | respond.getEmValue = getEmValue; 229 | function callMedia() { 230 | applyMedia(true); 231 | } 232 | if (w.addEventListener) { 233 | w.addEventListener("resize", callMedia, false); 234 | } else if (w.attachEvent) { 235 | w.attachEvent("onresize", callMedia); 236 | } 237 | })(this); 238 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Respond.js", 3 | "description": "min/max-width media query polyfill", 4 | "version": "1.4.2", 5 | "homepage": "https://github.com/scottjehl/Respond", 6 | "homepageShortened": "https://j.mp/respondjs", 7 | "author": { 8 | "name": "Scott Jehl", 9 | "email": "scott@filamentgroup.com", 10 | "url": "https://filamentgroup.com" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "https://github.com/scottjehl/Respond.git" 15 | }, 16 | "bugs": { 17 | "url": "https://github.com/scottjehl/Respond/issues" 18 | }, 19 | "licenses": [ 20 | { 21 | "type": "MIT", 22 | "url": "https://github.com/scottjehl/Respond/blob/master/LICENSE-MIT" 23 | } 24 | ], 25 | "devDependencies": { 26 | "grunt-cli":"~0.1", 27 | "grunt": "~0.4.0", 28 | "grunt-contrib-jshint": "~0.2.0", 29 | "grunt-contrib-qunit": "~0.3.0", 30 | "grunt-contrib-uglify": "0.2.7" 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/matchmedia.addListener.js: -------------------------------------------------------------------------------- 1 | /*! matchMedia() polyfill addListener/removeListener extension. Author & copyright (c) 2012: Scott Jehl. Dual MIT/BSD license */ 2 | (function( w ){ 3 | "use strict"; 4 | // Bail out for browsers that have addListener support 5 | if (w.matchMedia && w.matchMedia('all').addListener) { 6 | return false; 7 | } 8 | 9 | var localMatchMedia = w.matchMedia, 10 | hasMediaQueries = localMatchMedia('only all').matches, 11 | isListening = false, 12 | timeoutID = 0, // setTimeout for debouncing 'handleChange' 13 | queries = [], // Contains each 'mql' and associated 'listeners' if 'addListener' is used 14 | handleChange = function(evt) { 15 | // Debounce 16 | w.clearTimeout(timeoutID); 17 | 18 | timeoutID = w.setTimeout(function() { 19 | for (var i = 0, il = queries.length; i < il; i++) { 20 | var mql = queries[i].mql, 21 | listeners = queries[i].listeners || [], 22 | matches = localMatchMedia(mql.media).matches; 23 | 24 | // Update mql.matches value and call listeners 25 | // Fire listeners only if transitioning to or from matched state 26 | if (matches !== mql.matches) { 27 | mql.matches = matches; 28 | 29 | for (var j = 0, jl = listeners.length; j < jl; j++) { 30 | listeners[j].call(w, mql); 31 | } 32 | } 33 | } 34 | }, 30); 35 | }; 36 | 37 | w.matchMedia = function(media) { 38 | var mql = localMatchMedia(media), 39 | listeners = [], 40 | index = 0; 41 | 42 | mql.addListener = function(listener) { 43 | // Changes would not occur to css media type so return now (Affects IE <= 8) 44 | if (!hasMediaQueries) { 45 | return; 46 | } 47 | 48 | // Set up 'resize' listener for browsers that support CSS3 media queries (Not for IE <= 8) 49 | // There should only ever be 1 resize listener running for performance 50 | if (!isListening) { 51 | isListening = true; 52 | w.addEventListener('resize', handleChange, true); 53 | } 54 | 55 | // Push object only if it has not been pushed already 56 | if (index === 0) { 57 | index = queries.push({ 58 | mql : mql, 59 | listeners : listeners 60 | }); 61 | } 62 | 63 | listeners.push(listener); 64 | }; 65 | 66 | mql.removeListener = function(listener) { 67 | for (var i = 0, il = listeners.length; i < il; i++){ 68 | if (listeners[i] === listener){ 69 | listeners.splice(i, 1); 70 | } 71 | } 72 | }; 73 | 74 | return mql; 75 | }; 76 | }( this )); 77 | -------------------------------------------------------------------------------- /src/matchmedia.polyfill.js: -------------------------------------------------------------------------------- 1 | /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ 2 | /*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */ 3 | 4 | (function(w){ 5 | "use strict"; 6 | w.matchMedia = w.matchMedia || (function( doc, undefined ) { 7 | 8 | var bool, 9 | docElem = doc.documentElement, 10 | refNode = docElem.firstElementChild || docElem.firstChild, 11 | // fakeBody required for 12 | fakeBody = doc.createElement( "body" ), 13 | div = doc.createElement( "div" ); 14 | 15 | div.id = "mq-test-1"; 16 | div.style.cssText = "position:absolute;top:-100em"; 17 | fakeBody.style.background = "none"; 18 | fakeBody.appendChild(div); 19 | 20 | return function(q){ 21 | 22 | div.innerHTML = "­"; 23 | 24 | docElem.insertBefore( fakeBody, refNode ); 25 | bool = div.offsetWidth === 42; 26 | docElem.removeChild( fakeBody ); 27 | 28 | return { 29 | matches: bool, 30 | media: q 31 | }; 32 | 33 | }; 34 | 35 | }( w.document )); 36 | }( this )); 37 | -------------------------------------------------------------------------------- /src/respond.js: -------------------------------------------------------------------------------- 1 | /* Respond.js: min/max-width media query polyfill. (c) Scott Jehl. MIT Lic. j.mp/respondjs */ 2 | (function( w ){ 3 | 4 | "use strict"; 5 | 6 | //exposed namespace 7 | var respond = {}; 8 | w.respond = respond; 9 | 10 | //define update even in native-mq-supporting browsers, to avoid errors 11 | respond.update = function(){}; 12 | 13 | //define ajax obj 14 | var requestQueue = [], 15 | xmlHttp = (function() { 16 | var xmlhttpmethod = false; 17 | try { 18 | xmlhttpmethod = new w.XMLHttpRequest(); 19 | } 20 | catch( e ){ 21 | xmlhttpmethod = new w.ActiveXObject( "Microsoft.XMLHTTP" ); 22 | } 23 | return function(){ 24 | return xmlhttpmethod; 25 | }; 26 | })(), 27 | 28 | //tweaked Ajax functions from Quirksmode 29 | ajax = function( url, callback ) { 30 | var req = xmlHttp(); 31 | if (!req){ 32 | return; 33 | } 34 | req.open( "GET", url, true ); 35 | req.onreadystatechange = function () { 36 | if ( req.readyState !== 4 || req.status !== 200 && req.status !== 304 ){ 37 | return; 38 | } 39 | callback( req.responseText ); 40 | }; 41 | if ( req.readyState === 4 ){ 42 | return; 43 | } 44 | req.send( null ); 45 | }, 46 | isUnsupportedMediaQuery = function( query ) { 47 | return query.replace( respond.regex.minmaxwh, '' ).match( respond.regex.other ); 48 | }; 49 | 50 | //expose for testing 51 | respond.ajax = ajax; 52 | respond.queue = requestQueue; 53 | respond.unsupportedmq = isUnsupportedMediaQuery; 54 | respond.regex = { 55 | media: /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi, 56 | keyframes: /@(?:\-(?:o|moz|webkit)\-)?keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]*\}/gi, 57 | comments: /\/\*[^*]*\*+([^/][^*]*\*+)*\//gi, 58 | urls: /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, 59 | findStyles: /@media *([^\{]+)\{([\S\s]+?)$/, 60 | only: /(only\s+)?([a-zA-Z]+)\s?/, 61 | minw: /\(\s*min\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/, 62 | maxw: /\(\s*max\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/, 63 | minmaxwh: /\(\s*m(in|ax)\-(height|width)\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/gi, 64 | other: /\([^\)]*\)/g 65 | }; 66 | 67 | //expose media query support flag for external use 68 | respond.mediaQueriesSupported = w.matchMedia && w.matchMedia( "only all" ) !== null && w.matchMedia( "only all" ).matches; 69 | 70 | //if media queries are supported, exit here 71 | if( respond.mediaQueriesSupported ){ 72 | return; 73 | } 74 | 75 | //define vars 76 | var doc = w.document, 77 | docElem = doc.documentElement, 78 | mediastyles = [], 79 | rules = [], 80 | appendedEls = [], 81 | parsedSheets = {}, 82 | resizeThrottle = 30, 83 | head = doc.getElementsByTagName( "head" )[0] || docElem, 84 | base = doc.getElementsByTagName( "base" )[0], 85 | links = head.getElementsByTagName( "link" ), 86 | 87 | lastCall, 88 | resizeDefer, 89 | 90 | //cached container for 1em value, populated the first time it's needed 91 | eminpx, 92 | 93 | // returns the value of 1em in pixels 94 | getEmValue = function() { 95 | var ret, 96 | div = doc.createElement('div'), 97 | body = doc.body, 98 | originalHTMLFontSize = docElem.style.fontSize, 99 | originalBodyFontSize = body && body.style.fontSize, 100 | fakeUsed = false; 101 | 102 | div.style.cssText = "position:absolute;font-size:1em;width:1em"; 103 | 104 | if( !body ){ 105 | body = fakeUsed = doc.createElement( "body" ); 106 | body.style.background = "none"; 107 | } 108 | 109 | // 1em in a media query is the value of the default font size of the browser 110 | // reset docElem and body to ensure the correct value is returned 111 | docElem.style.fontSize = "100%"; 112 | body.style.fontSize = "100%"; 113 | 114 | body.appendChild( div ); 115 | 116 | if( fakeUsed ){ 117 | docElem.insertBefore( body, docElem.firstChild ); 118 | } 119 | 120 | ret = div.offsetWidth; 121 | 122 | if( fakeUsed ){ 123 | docElem.removeChild( body ); 124 | } 125 | else { 126 | body.removeChild( div ); 127 | } 128 | 129 | // restore the original values 130 | docElem.style.fontSize = originalHTMLFontSize; 131 | if( originalBodyFontSize ) { 132 | body.style.fontSize = originalBodyFontSize; 133 | } 134 | 135 | 136 | //also update eminpx before returning 137 | ret = eminpx = parseFloat(ret); 138 | 139 | return ret; 140 | }, 141 | 142 | //enable/disable styles 143 | applyMedia = function( fromResize ){ 144 | var name = "clientWidth", 145 | docElemProp = docElem[ name ], 146 | currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp, 147 | styleBlocks = {}, 148 | lastLink = links[ links.length-1 ], 149 | now = (new Date()).getTime(); 150 | 151 | //throttle resize calls 152 | if( fromResize && lastCall && now - lastCall < resizeThrottle ){ 153 | w.clearTimeout( resizeDefer ); 154 | resizeDefer = w.setTimeout( applyMedia, resizeThrottle ); 155 | return; 156 | } 157 | else { 158 | lastCall = now; 159 | } 160 | 161 | for( var i in mediastyles ){ 162 | if( mediastyles.hasOwnProperty( i ) ){ 163 | var thisstyle = mediastyles[ i ], 164 | min = thisstyle.minw, 165 | max = thisstyle.maxw, 166 | minnull = min === null, 167 | maxnull = max === null, 168 | em = "em"; 169 | 170 | if( !!min ){ 171 | min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); 172 | } 173 | if( !!max ){ 174 | max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); 175 | } 176 | 177 | // if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true 178 | if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){ 179 | if( !styleBlocks[ thisstyle.media ] ){ 180 | styleBlocks[ thisstyle.media ] = []; 181 | } 182 | styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] ); 183 | } 184 | } 185 | } 186 | 187 | //remove any existing respond style element(s) 188 | for( var j in appendedEls ){ 189 | if( appendedEls.hasOwnProperty( j ) ){ 190 | if( appendedEls[ j ] && appendedEls[ j ].parentNode === head ){ 191 | head.removeChild( appendedEls[ j ] ); 192 | } 193 | } 194 | } 195 | appendedEls.length = 0; 196 | 197 | //inject active styles, grouped by media type 198 | for( var k in styleBlocks ){ 199 | if( styleBlocks.hasOwnProperty( k ) ){ 200 | var ss = doc.createElement( "style" ), 201 | css = styleBlocks[ k ].join( "\n" ); 202 | 203 | ss.type = "text/css"; 204 | ss.media = k; 205 | 206 | //originally, ss was appended to a documentFragment and sheets were appended in bulk. 207 | //this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one! 208 | head.insertBefore( ss, lastLink.nextSibling ); 209 | 210 | if ( ss.styleSheet ){ 211 | ss.styleSheet.cssText = css; 212 | } 213 | else { 214 | ss.appendChild( doc.createTextNode( css ) ); 215 | } 216 | 217 | //push to appendedEls to track for later removal 218 | appendedEls.push( ss ); 219 | } 220 | } 221 | }, 222 | //find media blocks in css text, convert to style blocks 223 | translate = function( styles, href, media ){ 224 | var qs = styles.replace( respond.regex.comments, '' ) 225 | .replace( respond.regex.keyframes, '' ) 226 | .match( respond.regex.media ), 227 | ql = qs && qs.length || 0; 228 | 229 | //try to get CSS path 230 | href = href.substring( 0, href.lastIndexOf( "/" ) ); 231 | 232 | var repUrls = function( css ){ 233 | return css.replace( respond.regex.urls, "$1" + href + "$2$3" ); 234 | }, 235 | useMedia = !ql && media; 236 | 237 | //if path exists, tack on trailing slash 238 | if( href.length ){ href += "/"; } 239 | 240 | //if no internal queries exist, but media attr does, use that 241 | //note: this currently lacks support for situations where a media attr is specified on a link AND 242 | //its associated stylesheet has internal CSS media queries. 243 | //In those cases, the media attribute will currently be ignored. 244 | if( useMedia ){ 245 | ql = 1; 246 | } 247 | 248 | for( var i = 0; i < ql; i++ ){ 249 | var fullq, thisq, eachq, eql; 250 | 251 | //media attr 252 | if( useMedia ){ 253 | fullq = media; 254 | rules.push( repUrls( styles ) ); 255 | } 256 | //parse for styles 257 | else{ 258 | fullq = qs[ i ].match( respond.regex.findStyles ) && RegExp.$1; 259 | rules.push( RegExp.$2 && repUrls( RegExp.$2 ) ); 260 | } 261 | 262 | eachq = fullq.split( "," ); 263 | eql = eachq.length; 264 | 265 | for( var j = 0; j < eql; j++ ){ 266 | thisq = eachq[ j ]; 267 | 268 | if( isUnsupportedMediaQuery( thisq ) ) { 269 | continue; 270 | } 271 | 272 | mediastyles.push( { 273 | media : thisq.split( "(" )[ 0 ].match( respond.regex.only ) && RegExp.$2 || "all", 274 | rules : rules.length - 1, 275 | hasquery : thisq.indexOf("(") > -1, 276 | minw : thisq.match( respond.regex.minw ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ), 277 | maxw : thisq.match( respond.regex.maxw ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ) 278 | } ); 279 | } 280 | } 281 | 282 | applyMedia(); 283 | }, 284 | 285 | //recurse through request queue, get css text 286 | makeRequests = function(){ 287 | if( requestQueue.length ){ 288 | var thisRequest = requestQueue.shift(); 289 | 290 | ajax( thisRequest.href, function( styles ){ 291 | translate( styles, thisRequest.href, thisRequest.media ); 292 | parsedSheets[ thisRequest.href ] = true; 293 | 294 | // by wrapping recursive function call in setTimeout 295 | // we prevent "Stack overflow" error in IE7 296 | w.setTimeout(function(){ makeRequests(); },0); 297 | } ); 298 | } 299 | }, 300 | 301 | //loop stylesheets, send text content to translate 302 | ripCSS = function(){ 303 | 304 | for( var i = 0; i < links.length; i++ ){ 305 | var sheet = links[ i ], 306 | href = sheet.href, 307 | media = sheet.media, 308 | isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet"; 309 | 310 | //only links plz and prevent re-parsing 311 | if( !!href && isCSS && !parsedSheets[ href ] ){ 312 | // selectivizr exposes css through the rawCssText expando 313 | if (sheet.styleSheet && sheet.styleSheet.rawCssText) { 314 | translate( sheet.styleSheet.rawCssText, href, media ); 315 | parsedSheets[ href ] = true; 316 | } else { 317 | if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base) || 318 | href.replace( RegExp.$1, "" ).split( "/" )[0] === w.location.host ){ 319 | // IE7 doesn't handle urls that start with '//' for ajax request 320 | // manually add in the protocol 321 | if ( href.substring(0,2) === "//" ) { href = w.location.protocol + href; } 322 | requestQueue.push( { 323 | href: href, 324 | media: media 325 | } ); 326 | } 327 | } 328 | } 329 | } 330 | makeRequests(); 331 | }; 332 | 333 | //translate CSS 334 | ripCSS(); 335 | 336 | //expose update for re-running respond later on 337 | respond.update = ripCSS; 338 | 339 | //expose getEmValue 340 | respond.getEmValue = getEmValue; 341 | 342 | //adjust on resize 343 | function callMedia(){ 344 | applyMedia( true ); 345 | } 346 | 347 | if( w.addEventListener ){ 348 | w.addEventListener( "resize", callMedia, false ); 349 | } 350 | else if( w.attachEvent ){ 351 | w.attachEvent( "onresize", callMedia ); 352 | } 353 | })(this); 354 | -------------------------------------------------------------------------------- /test/test.css: -------------------------------------------------------------------------------- 1 | /* 2 | This is just a test file for making sure the script is working properly. 3 | If it is, the media queries below will change the body's background color depending on the browser width. 4 | For a realistic use case for media queries: read up on Responsive Web Design: 5 | http://www.alistapart.com/articles/responsive-web-design/ 6 | */ 7 | 8 | body { 9 | background: black; 10 | color: #333; 11 | font-family: Helvetica, sans-serif; 12 | } 13 | p { 14 | width: 60%; 15 | min-width: 18.75em; /* 300px @ 16px */ 16 | max-width: 43.75em; /* 700px @ 16px */ 17 | margin: 2em auto; 18 | background: #fff; 19 | padding: 20px; 20 | } 21 | a { 22 | color: #333; 23 | } 24 | 25 | /* hide the attribute-test element. test2.css will show it */ 26 | #attribute-test { 27 | display: none; 28 | } 29 | 30 | /*styles for 300 and up @ 16px!*/ 31 | /* The max-width declaration below blocks this from ever working */ 32 | @media only screen and (min-width: 18.75em){ 33 | body { 34 | background: yellow; 35 | } 36 | } 37 | 38 | 39 | /*styles for 480px - 620px @ 16px!*/ 40 | @media only screen and (min-width: 30em) and (max-width: 38.75em) { 41 | body { 42 | background: green; 43 | } 44 | } 45 | 46 | 47 | 48 | 49 | @media screen and (min-width: 38.75em),only print,projector{body{background:red;}} 50 | 51 | /*styles for 800px and up @ 16px!*/ 52 | @media screen and (min-width: 50em){ 53 | body { 54 | background: blue; 55 | } 56 | } 57 | 58 | /*styles for 1100px and up @ 16px!*/ 59 | @media screen and (min-width: 68.75em){ 60 | body { 61 | background: orange; 62 | } 63 | } 64 | 65 | /*one with pixels too! */ 66 | /* NOTE - if the user were to increase his browser font size to 20px (chrome: Large), 67 | the above (68.75em) media query will be incorrectly ignored!!! 68 | 69 | Assuming 20px browser setting, we would expect to see this progression: 70 | yellow > green > red > blue > NAVY > orange 71 | 72 | However, the orange never kicks in... which seems like a browser bug! 73 | Here's the math (assuming 20px browser setting): 74 | 1200/20 = 60em < 68.75em 75 | */ 76 | @media screen and (min-width: 1200px){ 77 | body { 78 | background: navy; 79 | } 80 | } 81 | 82 | @media only screen and (min-width: 1250px) and (min--moz-device-pixel-ratio: 1.5), 83 | only screen and (min-width: 1250px) and (-moz-min-device-pixel-ratio: 1.5), 84 | only screen and (min-width: 1250px) and (-o-min-device-pixel-ratio: 3/2), 85 | only screen and (min-width: 1250px) and (-webkit-min-device-pixel-ratio: 1.5), 86 | only screen and (min-width: 1250px) and (min-device-pixel-ratio: 1.5), 87 | only screen and (min-width: 1250px) and (min-resolution: 1.5dppx), 88 | screen and (min-width: 1250px) { 89 | 90 | body { 91 | background-color: pink; 92 | } 93 | } -------------------------------------------------------------------------------- /test/test.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Respond JS Test Page 6 | 7 | 8 | 9 | 10 | 11 |

This is just a visual test file, and an ugly one at that! For unit tests, visit the Respond.js unit test suite

12 | 13 |

The media queries in the included CSS file simply change the body's background color depending on the browser width. If you see any colors aside from black, then the media queries are working in your browser. You can resize your browser window to see it change on the fly.

14 | 15 |

For a realistic use case for media queries: read up on Responsive Web Design

16 | 17 |

Media-attributes are working too! This should be visible above 37.5em.

18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /test/test2.css: -------------------------------------------------------------------------------- 1 | /* this stylesheet was referenced via a link that had a media attr defined 2 | it should only apply on screen > 600px */ 3 | #attribute-test { 4 | display: block; 5 | color: #fff; 6 | background: black; 7 | text-align: center; 8 | } -------------------------------------------------------------------------------- /test/unit/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Respond.js Test Suite 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |

Respond.js Test Suite

17 |

18 |
19 |

20 |
    21 | 22 | 23 |
    24 | 25 | 26 |
    test
    27 | 28 | 29 | -------------------------------------------------------------------------------- /test/unit/qunit/qunit.css: -------------------------------------------------------------------------------- 1 | /** 2 | * QUnit v1.3.0pre - A JavaScript Unit Testing Framework 3 | * 4 | * http://docs.jquery.com/QUnit 5 | * 6 | * Copyright (c) 2011 John Resig, Jörn Zaefferer 7 | * Dual licensed under the MIT (MIT-LICENSE.txt) 8 | * or GPL (GPL-LICENSE.txt) licenses. 9 | */ 10 | 11 | /** Font Family and Sizes */ 12 | 13 | #qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult { 14 | font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif; 15 | } 16 | 17 | #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; } 18 | #qunit-tests { font-size: smaller; } 19 | 20 | 21 | /** Resets */ 22 | 23 | #qunit-tests, #qunit-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult { 24 | margin: 0; 25 | padding: 0; 26 | } 27 | 28 | 29 | /** Header */ 30 | 31 | #qunit-header { 32 | padding: 0.5em 0 0.5em 1em; 33 | 34 | color: #8699a4; 35 | background-color: #0d3349; 36 | 37 | font-size: 1.5em; 38 | line-height: 1em; 39 | font-weight: normal; 40 | 41 | border-radius: 15px 15px 0 0; 42 | -moz-border-radius: 15px 15px 0 0; 43 | -webkit-border-top-right-radius: 15px; 44 | -webkit-border-top-left-radius: 15px; 45 | } 46 | 47 | #qunit-header a { 48 | text-decoration: none; 49 | color: #c2ccd1; 50 | } 51 | 52 | #qunit-header a:hover, 53 | #qunit-header a:focus { 54 | color: #fff; 55 | } 56 | 57 | #qunit-banner { 58 | height: 5px; 59 | } 60 | 61 | #qunit-testrunner-toolbar { 62 | padding: 0.5em 0 0.5em 2em; 63 | color: #5E740B; 64 | background-color: #eee; 65 | } 66 | 67 | #qunit-userAgent { 68 | padding: 0.5em 0 0.5em 2.5em; 69 | background-color: #2b81af; 70 | color: #fff; 71 | text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px; 72 | } 73 | 74 | 75 | /** Tests: Pass/Fail */ 76 | 77 | #qunit-tests { 78 | list-style-position: inside; 79 | } 80 | 81 | #qunit-tests li { 82 | padding: 0.4em 0.5em 0.4em 2.5em; 83 | border-bottom: 1px solid #fff; 84 | list-style-position: inside; 85 | } 86 | 87 | #qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running { 88 | display: none; 89 | } 90 | 91 | #qunit-tests li strong { 92 | cursor: pointer; 93 | } 94 | 95 | #qunit-tests li a { 96 | padding: 0.5em; 97 | color: #c2ccd1; 98 | text-decoration: none; 99 | } 100 | #qunit-tests li a:hover, 101 | #qunit-tests li a:focus { 102 | color: #000; 103 | } 104 | 105 | #qunit-tests ol { 106 | margin-top: 0.5em; 107 | padding: 0.5em; 108 | 109 | background-color: #fff; 110 | 111 | border-radius: 15px; 112 | -moz-border-radius: 15px; 113 | -webkit-border-radius: 15px; 114 | 115 | box-shadow: inset 0px 2px 13px #999; 116 | -moz-box-shadow: inset 0px 2px 13px #999; 117 | -webkit-box-shadow: inset 0px 2px 13px #999; 118 | } 119 | 120 | #qunit-tests table { 121 | border-collapse: collapse; 122 | margin-top: .2em; 123 | } 124 | 125 | #qunit-tests th { 126 | text-align: right; 127 | vertical-align: top; 128 | padding: 0 .5em 0 0; 129 | } 130 | 131 | #qunit-tests td { 132 | vertical-align: top; 133 | } 134 | 135 | #qunit-tests pre { 136 | margin: 0; 137 | white-space: pre-wrap; 138 | word-wrap: break-word; 139 | } 140 | 141 | #qunit-tests del { 142 | background-color: #e0f2be; 143 | color: #374e0c; 144 | text-decoration: none; 145 | } 146 | 147 | #qunit-tests ins { 148 | background-color: #ffcaca; 149 | color: #500; 150 | text-decoration: none; 151 | } 152 | 153 | /*** Test Counts */ 154 | 155 | #qunit-tests b.counts { color: black; } 156 | #qunit-tests b.passed { color: #5E740B; } 157 | #qunit-tests b.failed { color: #710909; } 158 | 159 | #qunit-tests li li { 160 | margin: 0.5em; 161 | padding: 0.4em 0.5em 0.4em 0.5em; 162 | background-color: #fff; 163 | border-bottom: none; 164 | list-style-position: inside; 165 | } 166 | 167 | /*** Passing Styles */ 168 | 169 | #qunit-tests li li.pass { 170 | color: #5E740B; 171 | background-color: #fff; 172 | border-left: 26px solid #C6E746; 173 | } 174 | 175 | #qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; } 176 | #qunit-tests .pass .test-name { color: #366097; } 177 | 178 | #qunit-tests .pass .test-actual, 179 | #qunit-tests .pass .test-expected { color: #999999; } 180 | 181 | #qunit-banner.qunit-pass { background-color: #C6E746; } 182 | 183 | /*** Failing Styles */ 184 | 185 | #qunit-tests li li.fail { 186 | color: #710909; 187 | background-color: #fff; 188 | border-left: 26px solid #EE5757; 189 | white-space: pre; 190 | } 191 | 192 | #qunit-tests > li:last-child { 193 | border-radius: 0 0 15px 15px; 194 | -moz-border-radius: 0 0 15px 15px; 195 | -webkit-border-bottom-right-radius: 15px; 196 | -webkit-border-bottom-left-radius: 15px; 197 | } 198 | 199 | #qunit-tests .fail { color: #000000; background-color: #EE5757; } 200 | #qunit-tests .fail .test-name, 201 | #qunit-tests .fail .module-name { color: #000000; } 202 | 203 | #qunit-tests .fail .test-actual { color: #EE5757; } 204 | #qunit-tests .fail .test-expected { color: green; } 205 | 206 | #qunit-banner.qunit-fail { background-color: #EE5757; } 207 | 208 | 209 | /** Result */ 210 | 211 | #qunit-testresult { 212 | padding: 0.5em 0.5em 0.5em 2.5em; 213 | 214 | color: #2b81af; 215 | background-color: #D2E0E6; 216 | 217 | border-bottom: 1px solid white; 218 | } 219 | 220 | /** Fixture */ 221 | 222 | #qunit-fixture { 223 | position: absolute; 224 | top: -10000px; 225 | left: -10000px; 226 | } -------------------------------------------------------------------------------- /test/unit/qunit/qunit.js: -------------------------------------------------------------------------------- 1 | /** 2 | * QUnit v1.3.0pre - A JavaScript Unit Testing Framework 3 | * 4 | * http://docs.jquery.com/QUnit 5 | * 6 | * Copyright (c) 2011 John Resig, Jörn Zaefferer 7 | * Dual licensed under the MIT (MIT-LICENSE.txt) 8 | * or GPL (GPL-LICENSE.txt) licenses. 9 | */ 10 | 11 | (function(window) { 12 | 13 | var defined = { 14 | setTimeout: typeof window.setTimeout !== "undefined", 15 | sessionStorage: (function() { 16 | try { 17 | return !!sessionStorage.getItem; 18 | } catch(e) { 19 | return false; 20 | } 21 | })() 22 | }; 23 | 24 | var testId = 0, 25 | toString = Object.prototype.toString, 26 | hasOwn = Object.prototype.hasOwnProperty; 27 | 28 | var Test = function(name, testName, expected, testEnvironmentArg, async, callback) { 29 | this.name = name; 30 | this.testName = testName; 31 | this.expected = expected; 32 | this.testEnvironmentArg = testEnvironmentArg; 33 | this.async = async; 34 | this.callback = callback; 35 | this.assertions = []; 36 | }; 37 | Test.prototype = { 38 | init: function() { 39 | var tests = id("qunit-tests"); 40 | if (tests) { 41 | var b = document.createElement("strong"); 42 | b.innerHTML = "Running " + this.name; 43 | var li = document.createElement("li"); 44 | li.appendChild( b ); 45 | li.className = "running"; 46 | li.id = this.id = "test-output" + testId++; 47 | tests.appendChild( li ); 48 | } 49 | }, 50 | setup: function() { 51 | if (this.module != config.previousModule) { 52 | if ( config.previousModule ) { 53 | runLoggingCallbacks('moduleDone', QUnit, { 54 | name: config.previousModule, 55 | failed: config.moduleStats.bad, 56 | passed: config.moduleStats.all - config.moduleStats.bad, 57 | total: config.moduleStats.all 58 | } ); 59 | } 60 | config.previousModule = this.module; 61 | config.moduleStats = { all: 0, bad: 0 }; 62 | runLoggingCallbacks( 'moduleStart', QUnit, { 63 | name: this.module 64 | } ); 65 | } 66 | 67 | config.current = this; 68 | this.testEnvironment = extend({ 69 | setup: function() {}, 70 | teardown: function() {} 71 | }, this.moduleTestEnvironment); 72 | if (this.testEnvironmentArg) { 73 | extend(this.testEnvironment, this.testEnvironmentArg); 74 | } 75 | 76 | runLoggingCallbacks( 'testStart', QUnit, { 77 | name: this.testName, 78 | module: this.module 79 | }); 80 | 81 | // allow utility functions to access the current test environment 82 | // TODO why?? 83 | QUnit.current_testEnvironment = this.testEnvironment; 84 | 85 | try { 86 | if ( !config.pollution ) { 87 | saveGlobal(); 88 | } 89 | 90 | this.testEnvironment.setup.call(this.testEnvironment); 91 | } catch(e) { 92 | QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message ); 93 | } 94 | }, 95 | run: function() { 96 | config.current = this; 97 | if ( this.async ) { 98 | QUnit.stop(); 99 | } 100 | 101 | if ( config.notrycatch ) { 102 | this.callback.call(this.testEnvironment); 103 | return; 104 | } 105 | try { 106 | this.callback.call(this.testEnvironment); 107 | } catch(e) { 108 | fail("Test " + this.testName + " died, exception and test follows", e, this.callback); 109 | QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) ); 110 | // else next test will carry the responsibility 111 | saveGlobal(); 112 | 113 | // Restart the tests if they're blocking 114 | if ( config.blocking ) { 115 | QUnit.start(); 116 | } 117 | } 118 | }, 119 | teardown: function() { 120 | config.current = this; 121 | try { 122 | this.testEnvironment.teardown.call(this.testEnvironment); 123 | checkPollution(); 124 | } catch(e) { 125 | QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message ); 126 | } 127 | }, 128 | finish: function() { 129 | config.current = this; 130 | if ( this.expected != null && this.expected != this.assertions.length ) { 131 | QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" ); 132 | } 133 | 134 | var good = 0, bad = 0, 135 | tests = id("qunit-tests"); 136 | 137 | config.stats.all += this.assertions.length; 138 | config.moduleStats.all += this.assertions.length; 139 | 140 | if ( tests ) { 141 | var ol = document.createElement("ol"); 142 | 143 | for ( var i = 0; i < this.assertions.length; i++ ) { 144 | var assertion = this.assertions[i]; 145 | 146 | var li = document.createElement("li"); 147 | li.className = assertion.result ? "pass" : "fail"; 148 | li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); 149 | ol.appendChild( li ); 150 | 151 | if ( assertion.result ) { 152 | good++; 153 | } else { 154 | bad++; 155 | config.stats.bad++; 156 | config.moduleStats.bad++; 157 | } 158 | } 159 | 160 | // store result when possible 161 | if ( QUnit.config.reorder && defined.sessionStorage ) { 162 | if (bad) { 163 | sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad); 164 | } else { 165 | sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName); 166 | } 167 | } 168 | 169 | if (bad == 0) { 170 | ol.style.display = "none"; 171 | } 172 | 173 | var b = document.createElement("strong"); 174 | b.innerHTML = this.name + " (" + bad + ", " + good + ", " + this.assertions.length + ")"; 175 | 176 | var a = document.createElement("a"); 177 | a.innerHTML = "Rerun"; 178 | a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); 179 | 180 | addEvent(b, "click", function() { 181 | var next = b.nextSibling.nextSibling, 182 | display = next.style.display; 183 | next.style.display = display === "none" ? "block" : "none"; 184 | }); 185 | 186 | addEvent(b, "dblclick", function(e) { 187 | var target = e && e.target ? e.target : window.event.srcElement; 188 | if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { 189 | target = target.parentNode; 190 | } 191 | if ( window.location && target.nodeName.toLowerCase() === "strong" ) { 192 | window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); 193 | } 194 | }); 195 | 196 | var li = id(this.id); 197 | li.className = bad ? "fail" : "pass"; 198 | li.removeChild( li.firstChild ); 199 | li.appendChild( b ); 200 | li.appendChild( a ); 201 | li.appendChild( ol ); 202 | 203 | } else { 204 | for ( var i = 0; i < this.assertions.length; i++ ) { 205 | if ( !this.assertions[i].result ) { 206 | bad++; 207 | config.stats.bad++; 208 | config.moduleStats.bad++; 209 | } 210 | } 211 | } 212 | 213 | try { 214 | QUnit.reset(); 215 | } catch(e) { 216 | fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset); 217 | } 218 | 219 | runLoggingCallbacks( 'testDone', QUnit, { 220 | name: this.testName, 221 | module: this.module, 222 | failed: bad, 223 | passed: this.assertions.length - bad, 224 | total: this.assertions.length 225 | } ); 226 | }, 227 | 228 | queue: function() { 229 | var test = this; 230 | synchronize(function() { 231 | test.init(); 232 | }); 233 | function run() { 234 | // each of these can by async 235 | synchronize(function() { 236 | test.setup(); 237 | }); 238 | synchronize(function() { 239 | test.run(); 240 | }); 241 | synchronize(function() { 242 | test.teardown(); 243 | }); 244 | synchronize(function() { 245 | test.finish(); 246 | }); 247 | } 248 | // defer when previous test run passed, if storage is available 249 | var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName); 250 | if (bad) { 251 | run(); 252 | } else { 253 | synchronize(run, true); 254 | }; 255 | } 256 | 257 | }; 258 | 259 | var QUnit = { 260 | 261 | // call on start of module test to prepend name to all tests 262 | module: function(name, testEnvironment) { 263 | config.currentModule = name; 264 | config.currentModuleTestEnviroment = testEnvironment; 265 | }, 266 | 267 | asyncTest: function(testName, expected, callback) { 268 | if ( arguments.length === 2 ) { 269 | callback = expected; 270 | expected = null; 271 | } 272 | 273 | QUnit.test(testName, expected, callback, true); 274 | }, 275 | 276 | test: function(testName, expected, callback, async) { 277 | var name = '' + escapeInnerText(testName) + '', testEnvironmentArg; 278 | 279 | if ( arguments.length === 2 ) { 280 | callback = expected; 281 | expected = null; 282 | } 283 | // is 2nd argument a testEnvironment? 284 | if ( expected && typeof expected === 'object') { 285 | testEnvironmentArg = expected; 286 | expected = null; 287 | } 288 | 289 | if ( config.currentModule ) { 290 | name = '' + config.currentModule + ": " + name; 291 | } 292 | 293 | if ( !validTest(config.currentModule + ": " + testName) ) { 294 | return; 295 | } 296 | 297 | var test = new Test(name, testName, expected, testEnvironmentArg, async, callback); 298 | test.module = config.currentModule; 299 | test.moduleTestEnvironment = config.currentModuleTestEnviroment; 300 | test.queue(); 301 | }, 302 | 303 | /** 304 | * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. 305 | */ 306 | expect: function(asserts) { 307 | config.current.expected = asserts; 308 | }, 309 | 310 | /** 311 | * Asserts true. 312 | * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); 313 | */ 314 | ok: function(a, msg) { 315 | a = !!a; 316 | var details = { 317 | result: a, 318 | message: msg 319 | }; 320 | msg = escapeInnerText(msg); 321 | runLoggingCallbacks( 'log', QUnit, details ); 322 | config.current.assertions.push({ 323 | result: a, 324 | message: msg 325 | }); 326 | }, 327 | 328 | /** 329 | * Checks that the first two arguments are equal, with an optional message. 330 | * Prints out both actual and expected values. 331 | * 332 | * Prefered to ok( actual == expected, message ) 333 | * 334 | * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); 335 | * 336 | * @param Object actual 337 | * @param Object expected 338 | * @param String message (optional) 339 | */ 340 | equal: function(actual, expected, message) { 341 | QUnit.push(expected == actual, actual, expected, message); 342 | }, 343 | 344 | notEqual: function(actual, expected, message) { 345 | QUnit.push(expected != actual, actual, expected, message); 346 | }, 347 | 348 | deepEqual: function(actual, expected, message) { 349 | QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); 350 | }, 351 | 352 | notDeepEqual: function(actual, expected, message) { 353 | QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message); 354 | }, 355 | 356 | strictEqual: function(actual, expected, message) { 357 | QUnit.push(expected === actual, actual, expected, message); 358 | }, 359 | 360 | notStrictEqual: function(actual, expected, message) { 361 | QUnit.push(expected !== actual, actual, expected, message); 362 | }, 363 | 364 | raises: function(block, expected, message) { 365 | var actual, ok = false; 366 | 367 | if (typeof expected === 'string') { 368 | message = expected; 369 | expected = null; 370 | } 371 | 372 | try { 373 | block(); 374 | } catch (e) { 375 | actual = e; 376 | } 377 | 378 | if (actual) { 379 | // we don't want to validate thrown error 380 | if (!expected) { 381 | ok = true; 382 | // expected is a regexp 383 | } else if (QUnit.objectType(expected) === "regexp") { 384 | ok = expected.test(actual); 385 | // expected is a constructor 386 | } else if (actual instanceof expected) { 387 | ok = true; 388 | // expected is a validation function which returns true is validation passed 389 | } else if (expected.call({}, actual) === true) { 390 | ok = true; 391 | } 392 | } 393 | 394 | QUnit.ok(ok, message); 395 | }, 396 | 397 | start: function(count) { 398 | config.semaphore -= count || 1; 399 | if (config.semaphore > 0) { 400 | // don't start until equal number of stop-calls 401 | return; 402 | } 403 | if (config.semaphore < 0) { 404 | // ignore if start is called more often then stop 405 | config.semaphore = 0; 406 | } 407 | // A slight delay, to avoid any current callbacks 408 | if ( defined.setTimeout ) { 409 | window.setTimeout(function() { 410 | if (config.semaphore > 0) { 411 | return; 412 | } 413 | if ( config.timeout ) { 414 | clearTimeout(config.timeout); 415 | } 416 | 417 | config.blocking = false; 418 | process(true); 419 | }, 13); 420 | } else { 421 | config.blocking = false; 422 | process(true); 423 | } 424 | }, 425 | 426 | stop: function(count) { 427 | config.semaphore += count || 1; 428 | config.blocking = true; 429 | 430 | if ( config.testTimeout && defined.setTimeout ) { 431 | clearTimeout(config.timeout); 432 | config.timeout = window.setTimeout(function() { 433 | QUnit.ok( false, "Test timed out" ); 434 | config.semaphore = 1; 435 | QUnit.start(); 436 | }, config.testTimeout); 437 | } 438 | } 439 | }; 440 | 441 | //We want access to the constructor's prototype 442 | (function() { 443 | function F(){}; 444 | F.prototype = QUnit; 445 | QUnit = new F(); 446 | //Make F QUnit's constructor so that we can add to the prototype later 447 | QUnit.constructor = F; 448 | })(); 449 | 450 | // Backwards compatibility, deprecated 451 | QUnit.equals = QUnit.equal; 452 | QUnit.same = QUnit.deepEqual; 453 | 454 | // Maintain internal state 455 | var config = { 456 | // The queue of tests to run 457 | queue: [], 458 | 459 | // block until document ready 460 | blocking: true, 461 | 462 | // when enabled, show only failing tests 463 | // gets persisted through sessionStorage and can be changed in UI via checkbox 464 | hidepassed: false, 465 | 466 | // by default, run previously failed tests first 467 | // very useful in combination with "Hide passed tests" checked 468 | reorder: true, 469 | 470 | // by default, modify document.title when suite is done 471 | altertitle: true, 472 | 473 | urlConfig: ['noglobals', 'notrycatch'], 474 | 475 | //logging callback queues 476 | begin: [], 477 | done: [], 478 | log: [], 479 | testStart: [], 480 | testDone: [], 481 | moduleStart: [], 482 | moduleDone: [] 483 | }; 484 | 485 | // Load paramaters 486 | (function() { 487 | var location = window.location || { search: "", protocol: "file:" }, 488 | params = location.search.slice( 1 ).split( "&" ), 489 | length = params.length, 490 | urlParams = {}, 491 | current; 492 | 493 | if ( params[ 0 ] ) { 494 | for ( var i = 0; i < length; i++ ) { 495 | current = params[ i ].split( "=" ); 496 | current[ 0 ] = decodeURIComponent( current[ 0 ] ); 497 | // allow just a key to turn on a flag, e.g., test.html?noglobals 498 | current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; 499 | urlParams[ current[ 0 ] ] = current[ 1 ]; 500 | } 501 | } 502 | 503 | QUnit.urlParams = urlParams; 504 | config.filter = urlParams.filter; 505 | 506 | // Figure out if we're running the tests from a server or not 507 | QUnit.isLocal = !!(location.protocol === 'file:'); 508 | })(); 509 | 510 | // Expose the API as global variables, unless an 'exports' 511 | // object exists, in that case we assume we're in CommonJS 512 | if ( typeof exports === "undefined" || typeof require === "undefined" ) { 513 | extend(window, QUnit); 514 | window.QUnit = QUnit; 515 | } else { 516 | extend(exports, QUnit); 517 | exports.QUnit = QUnit; 518 | } 519 | 520 | // define these after exposing globals to keep them in these QUnit namespace only 521 | extend(QUnit, { 522 | config: config, 523 | 524 | // Initialize the configuration options 525 | init: function() { 526 | extend(config, { 527 | stats: { all: 0, bad: 0 }, 528 | moduleStats: { all: 0, bad: 0 }, 529 | started: +new Date, 530 | updateRate: 1000, 531 | blocking: false, 532 | autostart: true, 533 | autorun: false, 534 | filter: "", 535 | queue: [], 536 | semaphore: 0 537 | }); 538 | 539 | var tests = id( "qunit-tests" ), 540 | banner = id( "qunit-banner" ), 541 | result = id( "qunit-testresult" ); 542 | 543 | if ( tests ) { 544 | tests.innerHTML = ""; 545 | } 546 | 547 | if ( banner ) { 548 | banner.className = ""; 549 | } 550 | 551 | if ( result ) { 552 | result.parentNode.removeChild( result ); 553 | } 554 | 555 | if ( tests ) { 556 | result = document.createElement( "p" ); 557 | result.id = "qunit-testresult"; 558 | result.className = "result"; 559 | tests.parentNode.insertBefore( result, tests ); 560 | result.innerHTML = 'Running...
     '; 561 | } 562 | }, 563 | 564 | /** 565 | * Resets the test setup. Useful for tests that modify the DOM. 566 | * 567 | * If jQuery is available, uses jQuery's html(), otherwise just innerHTML. 568 | */ 569 | reset: function() { 570 | if ( window.jQuery ) { 571 | jQuery( "#qunit-fixture" ).html( config.fixture ); 572 | } else { 573 | var main = id( 'qunit-fixture' ); 574 | if ( main ) { 575 | main.innerHTML = config.fixture; 576 | } 577 | } 578 | }, 579 | 580 | /** 581 | * Trigger an event on an element. 582 | * 583 | * @example triggerEvent( document.body, "click" ); 584 | * 585 | * @param DOMElement elem 586 | * @param String type 587 | */ 588 | triggerEvent: function( elem, type, event ) { 589 | if ( document.createEvent ) { 590 | event = document.createEvent("MouseEvents"); 591 | event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 592 | 0, 0, 0, 0, 0, false, false, false, false, 0, null); 593 | elem.dispatchEvent( event ); 594 | 595 | } else if ( elem.fireEvent ) { 596 | elem.fireEvent("on"+type); 597 | } 598 | }, 599 | 600 | // Safe object type checking 601 | is: function( type, obj ) { 602 | return QUnit.objectType( obj ) == type; 603 | }, 604 | 605 | objectType: function( obj ) { 606 | if (typeof obj === "undefined") { 607 | return "undefined"; 608 | 609 | // consider: typeof null === object 610 | } 611 | if (obj === null) { 612 | return "null"; 613 | } 614 | 615 | var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || ''; 616 | 617 | switch (type) { 618 | case 'Number': 619 | if (isNaN(obj)) { 620 | return "nan"; 621 | } else { 622 | return "number"; 623 | } 624 | case 'String': 625 | case 'Boolean': 626 | case 'Array': 627 | case 'Date': 628 | case 'RegExp': 629 | case 'Function': 630 | return type.toLowerCase(); 631 | } 632 | if (typeof obj === "object") { 633 | return "object"; 634 | } 635 | return undefined; 636 | }, 637 | 638 | push: function(result, actual, expected, message) { 639 | var details = { 640 | result: result, 641 | message: message, 642 | actual: actual, 643 | expected: expected 644 | }; 645 | 646 | message = escapeInnerText(message) || (result ? "okay" : "failed"); 647 | message = '' + message + ""; 648 | expected = escapeInnerText(QUnit.jsDump.parse(expected)); 649 | actual = escapeInnerText(QUnit.jsDump.parse(actual)); 650 | var output = message + ''; 651 | if (actual != expected) { 652 | output += ''; 653 | output += ''; 654 | } 655 | if (!result) { 656 | var source = sourceFromStacktrace(); 657 | if (source) { 658 | details.source = source; 659 | output += ''; 660 | } 661 | } 662 | output += "
    Expected:
    ' + expected + '
    Result:
    ' + actual + '
    Diff:
    ' + QUnit.diff(expected, actual) +'
    Source:
    ' + escapeInnerText(source) + '
    "; 663 | 664 | runLoggingCallbacks( 'log', QUnit, details ); 665 | 666 | config.current.assertions.push({ 667 | result: !!result, 668 | message: output 669 | }); 670 | }, 671 | 672 | url: function( params ) { 673 | params = extend( extend( {}, QUnit.urlParams ), params ); 674 | var querystring = "?", 675 | key; 676 | for ( key in params ) { 677 | if ( !hasOwn.call( params, key ) ) { 678 | continue; 679 | } 680 | querystring += encodeURIComponent( key ) + "=" + 681 | encodeURIComponent( params[ key ] ) + "&"; 682 | } 683 | return window.location.pathname + querystring.slice( 0, -1 ); 684 | }, 685 | 686 | extend: extend, 687 | id: id, 688 | addEvent: addEvent 689 | }); 690 | 691 | //QUnit.constructor is set to the empty F() above so that we can add to it's prototype later 692 | //Doing this allows us to tell if the following methods have been overwritten on the actual 693 | //QUnit object, which is a deprecated way of using the callbacks. 694 | extend(QUnit.constructor.prototype, { 695 | // Logging callbacks; all receive a single argument with the listed properties 696 | // run test/logs.html for any related changes 697 | begin: registerLoggingCallback('begin'), 698 | // done: { failed, passed, total, runtime } 699 | done: registerLoggingCallback('done'), 700 | // log: { result, actual, expected, message } 701 | log: registerLoggingCallback('log'), 702 | // testStart: { name } 703 | testStart: registerLoggingCallback('testStart'), 704 | // testDone: { name, failed, passed, total } 705 | testDone: registerLoggingCallback('testDone'), 706 | // moduleStart: { name } 707 | moduleStart: registerLoggingCallback('moduleStart'), 708 | // moduleDone: { name, failed, passed, total } 709 | moduleDone: registerLoggingCallback('moduleDone') 710 | }); 711 | 712 | if ( typeof document === "undefined" || document.readyState === "complete" ) { 713 | config.autorun = true; 714 | } 715 | 716 | QUnit.load = function() { 717 | runLoggingCallbacks( 'begin', QUnit, {} ); 718 | 719 | // Initialize the config, saving the execution queue 720 | var oldconfig = extend({}, config); 721 | QUnit.init(); 722 | extend(config, oldconfig); 723 | 724 | config.blocking = false; 725 | 726 | var urlConfigHtml = '', len = config.urlConfig.length; 727 | for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) { 728 | config[val] = QUnit.urlParams[val]; 729 | urlConfigHtml += ''; 730 | } 731 | 732 | var userAgent = id("qunit-userAgent"); 733 | if ( userAgent ) { 734 | userAgent.innerHTML = navigator.userAgent; 735 | } 736 | var banner = id("qunit-header"); 737 | if ( banner ) { 738 | banner.innerHTML = ' ' + banner.innerHTML + ' ' + urlConfigHtml; 739 | addEvent( banner, "change", function( event ) { 740 | var params = {}; 741 | params[ event.target.name ] = event.target.checked ? true : undefined; 742 | window.location = QUnit.url( params ); 743 | }); 744 | } 745 | 746 | var toolbar = id("qunit-testrunner-toolbar"); 747 | if ( toolbar ) { 748 | var filter = document.createElement("input"); 749 | filter.type = "checkbox"; 750 | filter.id = "qunit-filter-pass"; 751 | addEvent( filter, "click", function() { 752 | var ol = document.getElementById("qunit-tests"); 753 | if ( filter.checked ) { 754 | ol.className = ol.className + " hidepass"; 755 | } else { 756 | var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; 757 | ol.className = tmp.replace(/ hidepass /, " "); 758 | } 759 | if ( defined.sessionStorage ) { 760 | if (filter.checked) { 761 | sessionStorage.setItem("qunit-filter-passed-tests", "true"); 762 | } else { 763 | sessionStorage.removeItem("qunit-filter-passed-tests"); 764 | } 765 | } 766 | }); 767 | if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) { 768 | filter.checked = true; 769 | var ol = document.getElementById("qunit-tests"); 770 | ol.className = ol.className + " hidepass"; 771 | } 772 | toolbar.appendChild( filter ); 773 | 774 | var label = document.createElement("label"); 775 | label.setAttribute("for", "qunit-filter-pass"); 776 | label.innerHTML = "Hide passed tests"; 777 | toolbar.appendChild( label ); 778 | } 779 | 780 | var main = id('qunit-fixture'); 781 | if ( main ) { 782 | config.fixture = main.innerHTML; 783 | } 784 | 785 | if (config.autostart) { 786 | QUnit.start(); 787 | } 788 | }; 789 | 790 | addEvent(window, "load", QUnit.load); 791 | 792 | // addEvent(window, "error") gives us a useless event object 793 | window.onerror = function( message, file, line ) { 794 | if ( QUnit.config.current ) { 795 | ok( false, message + ", " + file + ":" + line ); 796 | } else { 797 | test( "global failure", function() { 798 | ok( false, message + ", " + file + ":" + line ); 799 | }); 800 | } 801 | }; 802 | 803 | function done() { 804 | config.autorun = true; 805 | 806 | // Log the last module results 807 | if ( config.currentModule ) { 808 | runLoggingCallbacks( 'moduleDone', QUnit, { 809 | name: config.currentModule, 810 | failed: config.moduleStats.bad, 811 | passed: config.moduleStats.all - config.moduleStats.bad, 812 | total: config.moduleStats.all 813 | } ); 814 | } 815 | 816 | var banner = id("qunit-banner"), 817 | tests = id("qunit-tests"), 818 | runtime = +new Date - config.started, 819 | passed = config.stats.all - config.stats.bad, 820 | html = [ 821 | 'Tests completed in ', 822 | runtime, 823 | ' milliseconds.
    ', 824 | '', 825 | passed, 826 | ' tests of ', 827 | config.stats.all, 828 | ' passed, ', 829 | config.stats.bad, 830 | ' failed.' 831 | ].join(''); 832 | 833 | if ( banner ) { 834 | banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); 835 | } 836 | 837 | if ( tests ) { 838 | id( "qunit-testresult" ).innerHTML = html; 839 | } 840 | 841 | if ( config.altertitle && typeof document !== "undefined" && document.title ) { 842 | // show ✖ for good, ✔ for bad suite result in title 843 | // use escape sequences in case file gets loaded with non-utf-8-charset 844 | document.title = [ 845 | (config.stats.bad ? "\u2716" : "\u2714"), 846 | document.title.replace(/^[\u2714\u2716] /i, "") 847 | ].join(" "); 848 | } 849 | 850 | runLoggingCallbacks( 'done', QUnit, { 851 | failed: config.stats.bad, 852 | passed: passed, 853 | total: config.stats.all, 854 | runtime: runtime 855 | } ); 856 | } 857 | 858 | function validTest( name ) { 859 | var filter = config.filter, 860 | run = false; 861 | 862 | if ( !filter ) { 863 | return true; 864 | } 865 | 866 | var not = filter.charAt( 0 ) === "!"; 867 | if ( not ) { 868 | filter = filter.slice( 1 ); 869 | } 870 | 871 | if ( name.indexOf( filter ) !== -1 ) { 872 | return !not; 873 | } 874 | 875 | if ( not ) { 876 | run = true; 877 | } 878 | 879 | return run; 880 | } 881 | 882 | // so far supports only Firefox, Chrome and Opera (buggy) 883 | // could be extended in the future to use something like https://github.com/csnover/TraceKit 884 | function sourceFromStacktrace() { 885 | try { 886 | throw new Error(); 887 | } catch ( e ) { 888 | if (e.stacktrace) { 889 | // Opera 890 | return e.stacktrace.split("\n")[6]; 891 | } else if (e.stack) { 892 | // Firefox, Chrome 893 | return e.stack.split("\n")[4]; 894 | } else if (e.sourceURL) { 895 | // Safari, PhantomJS 896 | // TODO sourceURL points at the 'throw new Error' line above, useless 897 | //return e.sourceURL + ":" + e.line; 898 | } 899 | } 900 | } 901 | 902 | function escapeInnerText(s) { 903 | if (!s) { 904 | return ""; 905 | } 906 | s = s + ""; 907 | return s.replace(/[\&<>]/g, function(s) { 908 | switch(s) { 909 | case "&": return "&"; 910 | case "<": return "<"; 911 | case ">": return ">"; 912 | default: return s; 913 | } 914 | }); 915 | } 916 | 917 | function synchronize( callback, last ) { 918 | config.queue.push( callback ); 919 | 920 | if ( config.autorun && !config.blocking ) { 921 | process(last); 922 | } 923 | } 924 | 925 | function process( last ) { 926 | var start = new Date().getTime(); 927 | config.depth = config.depth ? config.depth + 1 : 1; 928 | 929 | while ( config.queue.length && !config.blocking ) { 930 | if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { 931 | config.queue.shift()(); 932 | } else { 933 | window.setTimeout( function(){ 934 | process( last ); 935 | }, 13 ); 936 | break; 937 | } 938 | } 939 | config.depth--; 940 | if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { 941 | done(); 942 | } 943 | } 944 | 945 | function saveGlobal() { 946 | config.pollution = []; 947 | 948 | if ( config.noglobals ) { 949 | for ( var key in window ) { 950 | if ( !hasOwn.call( window, key ) ) { 951 | continue; 952 | } 953 | config.pollution.push( key ); 954 | } 955 | } 956 | } 957 | 958 | function checkPollution( name ) { 959 | var old = config.pollution; 960 | saveGlobal(); 961 | 962 | var newGlobals = diff( config.pollution, old ); 963 | if ( newGlobals.length > 0 ) { 964 | ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); 965 | } 966 | 967 | var deletedGlobals = diff( old, config.pollution ); 968 | if ( deletedGlobals.length > 0 ) { 969 | ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); 970 | } 971 | } 972 | 973 | // returns a new Array with the elements that are in a but not in b 974 | function diff( a, b ) { 975 | var result = a.slice(); 976 | for ( var i = 0; i < result.length; i++ ) { 977 | for ( var j = 0; j < b.length; j++ ) { 978 | if ( result[i] === b[j] ) { 979 | result.splice(i, 1); 980 | i--; 981 | break; 982 | } 983 | } 984 | } 985 | return result; 986 | } 987 | 988 | function fail(message, exception, callback) { 989 | if ( typeof console !== "undefined" && console.error && console.warn ) { 990 | console.error(message); 991 | console.error(exception); 992 | console.error(exception.stack); 993 | console.warn(callback.toString()); 994 | 995 | } else if ( window.opera && opera.postError ) { 996 | opera.postError(message, exception, callback.toString); 997 | } 998 | } 999 | 1000 | function extend(a, b) { 1001 | for ( var prop in b ) { 1002 | if ( b[prop] === undefined ) { 1003 | delete a[prop]; 1004 | 1005 | // Avoid "Member not found" error in IE8 caused by setting window.constructor 1006 | } else if ( prop !== "constructor" || a !== window ) { 1007 | a[prop] = b[prop]; 1008 | } 1009 | } 1010 | 1011 | return a; 1012 | } 1013 | 1014 | function addEvent(elem, type, fn) { 1015 | if ( elem.addEventListener ) { 1016 | elem.addEventListener( type, fn, false ); 1017 | } else if ( elem.attachEvent ) { 1018 | elem.attachEvent( "on" + type, fn ); 1019 | } else { 1020 | fn(); 1021 | } 1022 | } 1023 | 1024 | function id(name) { 1025 | return !!(typeof document !== "undefined" && document && document.getElementById) && 1026 | document.getElementById( name ); 1027 | } 1028 | 1029 | function registerLoggingCallback(key){ 1030 | return function(callback){ 1031 | config[key].push( callback ); 1032 | }; 1033 | } 1034 | 1035 | // Supports deprecated method of completely overwriting logging callbacks 1036 | function runLoggingCallbacks(key, scope, args) { 1037 | //debugger; 1038 | var callbacks; 1039 | if ( QUnit.hasOwnProperty(key) ) { 1040 | QUnit[key].call(scope, args); 1041 | } else { 1042 | callbacks = config[key]; 1043 | for( var i = 0; i < callbacks.length; i++ ) { 1044 | callbacks[i].call( scope, args ); 1045 | } 1046 | } 1047 | } 1048 | 1049 | // Test for equality any JavaScript type. 1050 | // Author: Philippe Rathé 1051 | QUnit.equiv = function () { 1052 | 1053 | var innerEquiv; // the real equiv function 1054 | var callers = []; // stack to decide between skip/abort functions 1055 | var parents = []; // stack to avoiding loops from circular referencing 1056 | 1057 | // Call the o related callback with the given arguments. 1058 | function bindCallbacks(o, callbacks, args) { 1059 | var prop = QUnit.objectType(o); 1060 | if (prop) { 1061 | if (QUnit.objectType(callbacks[prop]) === "function") { 1062 | return callbacks[prop].apply(callbacks, args); 1063 | } else { 1064 | return callbacks[prop]; // or undefined 1065 | } 1066 | } 1067 | } 1068 | 1069 | var getProto = Object.getPrototypeOf || function (obj) { 1070 | return obj.__proto__; 1071 | }; 1072 | 1073 | var callbacks = function () { 1074 | 1075 | // for string, boolean, number and null 1076 | function useStrictEquality(b, a) { 1077 | if (b instanceof a.constructor || a instanceof b.constructor) { 1078 | // to catch short annotaion VS 'new' annotation of a 1079 | // declaration 1080 | // e.g. var i = 1; 1081 | // var j = new Number(1); 1082 | return a == b; 1083 | } else { 1084 | return a === b; 1085 | } 1086 | } 1087 | 1088 | return { 1089 | "string" : useStrictEquality, 1090 | "boolean" : useStrictEquality, 1091 | "number" : useStrictEquality, 1092 | "null" : useStrictEquality, 1093 | "undefined" : useStrictEquality, 1094 | 1095 | "nan" : function(b) { 1096 | return isNaN(b); 1097 | }, 1098 | 1099 | "date" : function(b, a) { 1100 | return QUnit.objectType(b) === "date" 1101 | && a.valueOf() === b.valueOf(); 1102 | }, 1103 | 1104 | "regexp" : function(b, a) { 1105 | return QUnit.objectType(b) === "regexp" 1106 | && a.source === b.source && // the regex itself 1107 | a.global === b.global && // and its modifers 1108 | // (gmi) ... 1109 | a.ignoreCase === b.ignoreCase 1110 | && a.multiline === b.multiline; 1111 | }, 1112 | 1113 | // - skip when the property is a method of an instance (OOP) 1114 | // - abort otherwise, 1115 | // initial === would have catch identical references anyway 1116 | "function" : function() { 1117 | var caller = callers[callers.length - 1]; 1118 | return caller !== Object && typeof caller !== "undefined"; 1119 | }, 1120 | 1121 | "array" : function(b, a) { 1122 | var i, j, loop; 1123 | var len; 1124 | 1125 | // b could be an object literal here 1126 | if (!(QUnit.objectType(b) === "array")) { 1127 | return false; 1128 | } 1129 | 1130 | len = a.length; 1131 | if (len !== b.length) { // safe and faster 1132 | return false; 1133 | } 1134 | 1135 | // track reference to avoid circular references 1136 | parents.push(a); 1137 | for (i = 0; i < len; i++) { 1138 | loop = false; 1139 | for (j = 0; j < parents.length; j++) { 1140 | if (parents[j] === a[i]) { 1141 | loop = true;// dont rewalk array 1142 | } 1143 | } 1144 | if (!loop && !innerEquiv(a[i], b[i])) { 1145 | parents.pop(); 1146 | return false; 1147 | } 1148 | } 1149 | parents.pop(); 1150 | return true; 1151 | }, 1152 | 1153 | "object" : function(b, a) { 1154 | var i, j, loop; 1155 | var eq = true; // unless we can proove it 1156 | var aProperties = [], bProperties = []; // collection of 1157 | // strings 1158 | 1159 | // comparing constructors is more strict than using 1160 | // instanceof 1161 | if (a.constructor !== b.constructor) { 1162 | // Allow objects with no prototype to be equivalent to 1163 | // objects with Object as their constructor. 1164 | if (!((getProto(a) === null && getProto(b) === Object.prototype) || 1165 | (getProto(b) === null && getProto(a) === Object.prototype))) 1166 | { 1167 | return false; 1168 | } 1169 | } 1170 | 1171 | // stack constructor before traversing properties 1172 | callers.push(a.constructor); 1173 | // track reference to avoid circular references 1174 | parents.push(a); 1175 | 1176 | for (i in a) { // be strict: don't ensures hasOwnProperty 1177 | // and go deep 1178 | loop = false; 1179 | for (j = 0; j < parents.length; j++) { 1180 | if (parents[j] === a[i]) 1181 | loop = true; // don't go down the same path 1182 | // twice 1183 | } 1184 | aProperties.push(i); // collect a's properties 1185 | 1186 | if (!loop && !innerEquiv(a[i], b[i])) { 1187 | eq = false; 1188 | break; 1189 | } 1190 | } 1191 | 1192 | callers.pop(); // unstack, we are done 1193 | parents.pop(); 1194 | 1195 | for (i in b) { 1196 | bProperties.push(i); // collect b's properties 1197 | } 1198 | 1199 | // Ensures identical properties name 1200 | return eq 1201 | && innerEquiv(aProperties.sort(), bProperties 1202 | .sort()); 1203 | } 1204 | }; 1205 | }(); 1206 | 1207 | innerEquiv = function() { // can take multiple arguments 1208 | var args = Array.prototype.slice.apply(arguments); 1209 | if (args.length < 2) { 1210 | return true; // end transition 1211 | } 1212 | 1213 | return (function(a, b) { 1214 | if (a === b) { 1215 | return true; // catch the most you can 1216 | } else if (a === null || b === null || typeof a === "undefined" 1217 | || typeof b === "undefined" 1218 | || QUnit.objectType(a) !== QUnit.objectType(b)) { 1219 | return false; // don't lose time with error prone cases 1220 | } else { 1221 | return bindCallbacks(a, callbacks, [ b, a ]); 1222 | } 1223 | 1224 | // apply transition with (1..n) arguments 1225 | })(args[0], args[1]) 1226 | && arguments.callee.apply(this, args.splice(1, 1227 | args.length - 1)); 1228 | }; 1229 | 1230 | return innerEquiv; 1231 | 1232 | }(); 1233 | 1234 | /** 1235 | * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | 1236 | * http://flesler.blogspot.com Licensed under BSD 1237 | * (https://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 1238 | * 1239 | * @projectDescription Advanced and extensible data dumping for Javascript. 1240 | * @version 1.0.0 1241 | * @author Ariel Flesler 1242 | * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} 1243 | */ 1244 | QUnit.jsDump = (function() { 1245 | function quote( str ) { 1246 | return '"' + str.toString().replace(/"/g, '\\"') + '"'; 1247 | }; 1248 | function literal( o ) { 1249 | return o + ''; 1250 | }; 1251 | function join( pre, arr, post ) { 1252 | var s = jsDump.separator(), 1253 | base = jsDump.indent(), 1254 | inner = jsDump.indent(1); 1255 | if ( arr.join ) 1256 | arr = arr.join( ',' + s + inner ); 1257 | if ( !arr ) 1258 | return pre + post; 1259 | return [ pre, inner + arr, base + post ].join(s); 1260 | }; 1261 | function array( arr, stack ) { 1262 | var i = arr.length, ret = Array(i); 1263 | this.up(); 1264 | while ( i-- ) 1265 | ret[i] = this.parse( arr[i] , undefined , stack); 1266 | this.down(); 1267 | return join( '[', ret, ']' ); 1268 | }; 1269 | 1270 | var reName = /^function (\w+)/; 1271 | 1272 | var jsDump = { 1273 | parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance 1274 | stack = stack || [ ]; 1275 | var parser = this.parsers[ type || this.typeOf(obj) ]; 1276 | type = typeof parser; 1277 | var inStack = inArray(obj, stack); 1278 | if (inStack != -1) { 1279 | return 'recursion('+(inStack - stack.length)+')'; 1280 | } 1281 | //else 1282 | if (type == 'function') { 1283 | stack.push(obj); 1284 | var res = parser.call( this, obj, stack ); 1285 | stack.pop(); 1286 | return res; 1287 | } 1288 | // else 1289 | return (type == 'string') ? parser : this.parsers.error; 1290 | }, 1291 | typeOf:function( obj ) { 1292 | var type; 1293 | if ( obj === null ) { 1294 | type = "null"; 1295 | } else if (typeof obj === "undefined") { 1296 | type = "undefined"; 1297 | } else if (QUnit.is("RegExp", obj)) { 1298 | type = "regexp"; 1299 | } else if (QUnit.is("Date", obj)) { 1300 | type = "date"; 1301 | } else if (QUnit.is("Function", obj)) { 1302 | type = "function"; 1303 | } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") { 1304 | type = "window"; 1305 | } else if (obj.nodeType === 9) { 1306 | type = "document"; 1307 | } else if (obj.nodeType) { 1308 | type = "node"; 1309 | } else if ( 1310 | // native arrays 1311 | toString.call( obj ) === "[object Array]" || 1312 | // NodeList objects 1313 | ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) 1314 | ) { 1315 | type = "array"; 1316 | } else { 1317 | type = typeof obj; 1318 | } 1319 | return type; 1320 | }, 1321 | separator:function() { 1322 | return this.multiline ? this.HTML ? '
    ' : '\n' : this.HTML ? ' ' : ' '; 1323 | }, 1324 | indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing 1325 | if ( !this.multiline ) 1326 | return ''; 1327 | var chr = this.indentChar; 1328 | if ( this.HTML ) 1329 | chr = chr.replace(/\t/g,' ').replace(/ /g,' '); 1330 | return Array( this._depth_ + (extra||0) ).join(chr); 1331 | }, 1332 | up:function( a ) { 1333 | this._depth_ += a || 1; 1334 | }, 1335 | down:function( a ) { 1336 | this._depth_ -= a || 1; 1337 | }, 1338 | setParser:function( name, parser ) { 1339 | this.parsers[name] = parser; 1340 | }, 1341 | // The next 3 are exposed so you can use them 1342 | quote:quote, 1343 | literal:literal, 1344 | join:join, 1345 | // 1346 | _depth_: 1, 1347 | // This is the list of parsers, to modify them, use jsDump.setParser 1348 | parsers:{ 1349 | window: '[Window]', 1350 | document: '[Document]', 1351 | error:'[ERROR]', //when no parser is found, shouldn't happen 1352 | unknown: '[Unknown]', 1353 | 'null':'null', 1354 | 'undefined':'undefined', 1355 | 'function':function( fn ) { 1356 | var ret = 'function', 1357 | name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE 1358 | if ( name ) 1359 | ret += ' ' + name; 1360 | ret += '('; 1361 | 1362 | ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join(''); 1363 | return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' ); 1364 | }, 1365 | array: array, 1366 | nodelist: array, 1367 | arguments: array, 1368 | object:function( map, stack ) { 1369 | var ret = [ ]; 1370 | QUnit.jsDump.up(); 1371 | for ( var key in map ) { 1372 | var val = map[key]; 1373 | ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack)); 1374 | } 1375 | QUnit.jsDump.down(); 1376 | return join( '{', ret, '}' ); 1377 | }, 1378 | node:function( node ) { 1379 | var open = QUnit.jsDump.HTML ? '<' : '<', 1380 | close = QUnit.jsDump.HTML ? '>' : '>'; 1381 | 1382 | var tag = node.nodeName.toLowerCase(), 1383 | ret = open + tag; 1384 | 1385 | for ( var a in QUnit.jsDump.DOMAttrs ) { 1386 | var val = node[QUnit.jsDump.DOMAttrs[a]]; 1387 | if ( val ) 1388 | ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' ); 1389 | } 1390 | return ret + close + open + '/' + tag + close; 1391 | }, 1392 | functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function 1393 | var l = fn.length; 1394 | if ( !l ) return ''; 1395 | 1396 | var args = Array(l); 1397 | while ( l-- ) 1398 | args[l] = String.fromCharCode(97+l);//97 is 'a' 1399 | return ' ' + args.join(', ') + ' '; 1400 | }, 1401 | key:quote, //object calls it internally, the key part of an item in a map 1402 | functionCode:'[code]', //function calls it internally, it's the content of the function 1403 | attribute:quote, //node calls it internally, it's an html attribute value 1404 | string:quote, 1405 | date:quote, 1406 | regexp:literal, //regex 1407 | number:literal, 1408 | 'boolean':literal 1409 | }, 1410 | DOMAttrs:{//attributes to dump from nodes, name=>realName 1411 | id:'id', 1412 | name:'name', 1413 | 'class':'className' 1414 | }, 1415 | HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) 1416 | indentChar:' ',//indentation unit 1417 | multiline:true //if true, items in a collection, are separated by a \n, else just a space. 1418 | }; 1419 | 1420 | return jsDump; 1421 | })(); 1422 | 1423 | // from Sizzle.js 1424 | function getText( elems ) { 1425 | var ret = "", elem; 1426 | 1427 | for ( var i = 0; elems[i]; i++ ) { 1428 | elem = elems[i]; 1429 | 1430 | // Get the text from text nodes and CDATA nodes 1431 | if ( elem.nodeType === 3 || elem.nodeType === 4 ) { 1432 | ret += elem.nodeValue; 1433 | 1434 | // Traverse everything else, except comment nodes 1435 | } else if ( elem.nodeType !== 8 ) { 1436 | ret += getText( elem.childNodes ); 1437 | } 1438 | } 1439 | 1440 | return ret; 1441 | }; 1442 | 1443 | //from jquery.js 1444 | function inArray( elem, array ) { 1445 | if ( array.indexOf ) { 1446 | return array.indexOf( elem ); 1447 | } 1448 | 1449 | for ( var i = 0, length = array.length; i < length; i++ ) { 1450 | if ( array[ i ] === elem ) { 1451 | return i; 1452 | } 1453 | } 1454 | 1455 | return -1; 1456 | } 1457 | 1458 | /* 1459 | * Javascript Diff Algorithm 1460 | * By John Resig (http://ejohn.org/) 1461 | * Modified by Chu Alan "sprite" 1462 | * 1463 | * Released under the MIT license. 1464 | * 1465 | * More Info: 1466 | * http://ejohn.org/projects/javascript-diff-algorithm/ 1467 | * 1468 | * Usage: QUnit.diff(expected, actual) 1469 | * 1470 | * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick brown fox jumped jumps over" 1471 | */ 1472 | QUnit.diff = (function() { 1473 | function diff(o, n) { 1474 | var ns = {}; 1475 | var os = {}; 1476 | 1477 | for (var i = 0; i < n.length; i++) { 1478 | if (ns[n[i]] == null) 1479 | ns[n[i]] = { 1480 | rows: [], 1481 | o: null 1482 | }; 1483 | ns[n[i]].rows.push(i); 1484 | } 1485 | 1486 | for (var i = 0; i < o.length; i++) { 1487 | if (os[o[i]] == null) 1488 | os[o[i]] = { 1489 | rows: [], 1490 | n: null 1491 | }; 1492 | os[o[i]].rows.push(i); 1493 | } 1494 | 1495 | for (var i in ns) { 1496 | if ( !hasOwn.call( ns, i ) ) { 1497 | continue; 1498 | } 1499 | if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) { 1500 | n[ns[i].rows[0]] = { 1501 | text: n[ns[i].rows[0]], 1502 | row: os[i].rows[0] 1503 | }; 1504 | o[os[i].rows[0]] = { 1505 | text: o[os[i].rows[0]], 1506 | row: ns[i].rows[0] 1507 | }; 1508 | } 1509 | } 1510 | 1511 | for (var i = 0; i < n.length - 1; i++) { 1512 | if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && 1513 | n[i + 1] == o[n[i].row + 1]) { 1514 | n[i + 1] = { 1515 | text: n[i + 1], 1516 | row: n[i].row + 1 1517 | }; 1518 | o[n[i].row + 1] = { 1519 | text: o[n[i].row + 1], 1520 | row: i + 1 1521 | }; 1522 | } 1523 | } 1524 | 1525 | for (var i = n.length - 1; i > 0; i--) { 1526 | if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && 1527 | n[i - 1] == o[n[i].row - 1]) { 1528 | n[i - 1] = { 1529 | text: n[i - 1], 1530 | row: n[i].row - 1 1531 | }; 1532 | o[n[i].row - 1] = { 1533 | text: o[n[i].row - 1], 1534 | row: i - 1 1535 | }; 1536 | } 1537 | } 1538 | 1539 | return { 1540 | o: o, 1541 | n: n 1542 | }; 1543 | } 1544 | 1545 | return function(o, n) { 1546 | o = o.replace(/\s+$/, ''); 1547 | n = n.replace(/\s+$/, ''); 1548 | var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/)); 1549 | 1550 | var str = ""; 1551 | 1552 | var oSpace = o.match(/\s+/g); 1553 | if (oSpace == null) { 1554 | oSpace = [" "]; 1555 | } 1556 | else { 1557 | oSpace.push(" "); 1558 | } 1559 | var nSpace = n.match(/\s+/g); 1560 | if (nSpace == null) { 1561 | nSpace = [" "]; 1562 | } 1563 | else { 1564 | nSpace.push(" "); 1565 | } 1566 | 1567 | if (out.n.length == 0) { 1568 | for (var i = 0; i < out.o.length; i++) { 1569 | str += '' + out.o[i] + oSpace[i] + ""; 1570 | } 1571 | } 1572 | else { 1573 | if (out.n[0].text == null) { 1574 | for (n = 0; n < out.o.length && out.o[n].text == null; n++) { 1575 | str += '' + out.o[n] + oSpace[n] + ""; 1576 | } 1577 | } 1578 | 1579 | for (var i = 0; i < out.n.length; i++) { 1580 | if (out.n[i].text == null) { 1581 | str += '' + out.n[i] + nSpace[i] + ""; 1582 | } 1583 | else { 1584 | var pre = ""; 1585 | 1586 | for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) { 1587 | pre += '' + out.o[n] + oSpace[n] + ""; 1588 | } 1589 | str += " " + out.n[i].text + nSpace[i] + pre; 1590 | } 1591 | } 1592 | } 1593 | 1594 | return str; 1595 | }; 1596 | })(); 1597 | 1598 | })(this); 1599 | -------------------------------------------------------------------------------- /test/unit/test-with-comment.css: -------------------------------------------------------------------------------- 1 | /* this is a comment 2 | * 3 | */ 4 | 5 | @media (min-width: 1px) { 6 | 7 | /* see issue #22 */ 8 | /* @media {} */ 9 | /* @media { 10 | } */ 11 | 12 | /* this is a comment 13 | * 14 | */ 15 | 16 | /* * / /* 17 | Will this strip right? 18 | */ 19 | body { 20 | color: red; 21 | /* TODO This edge case is not currently supported */ 22 | content: "content /* this should not strip */"; 23 | } 24 | 25 | /* this is a comment */ 26 | 27 | /* see issue #22 */ 28 | /* @media */ 29 | } 30 | -------------------------------------------------------------------------------- /test/unit/test-with-dpr.css: -------------------------------------------------------------------------------- 1 | @media 2 | only screen and (max-width: 1004px) and (min--moz-device-pixel-ratio: 1.5), 3 | only screen and (max-width: 1004px) and (-moz-min-device-pixel-ratio: 1.5), 4 | only screen and (max-width: 1004px) and (-o-min-device-pixel-ratio: 3/2), 5 | only screen and (max-width: 1004px) and (-webkit-min-device-pixel-ratio: 1.5), 6 | only screen and (max-width: 1004px) and (min-device-pixel-ratio: 1.5), 7 | only screen and (max-width: 1004px) and (min-resolution: 1.5dppx) { 8 | 9 | 10 | } -------------------------------------------------------------------------------- /test/unit/test-with-keyframe.css: -------------------------------------------------------------------------------- 1 | @media (min-width: 1px) { 2 | 3 | @-webkit-keyframes NAME-YOUR-ANIMATION { 4 | 0% { opacity: 0; } 5 | 100% { opacity: 1; } 6 | } 7 | @keyframes NAME-YOUR-ANIMATION { 8 | 0% { opacity: 0; } 9 | 100% { opacity: 1; } 10 | } 11 | 12 | body { 13 | color: red; 14 | } 15 | } -------------------------------------------------------------------------------- /test/unit/test.css: -------------------------------------------------------------------------------- 1 | 2 | 3 | .launcher #qunit-testrunner-toolbar, 4 | .launcher #qunit-userAgent, 5 | .launcher #qunit-tests, 6 | .launcher #qunit-testresult { 7 | display: none; 8 | } 9 | .launcher #launcher { 10 | 11 | font: 1.5em/1 bold Helvetica, sans-serif; 12 | } 13 | 14 | #testelem { 15 | width: 50px; 16 | overflow: hidden; 17 | display: block; 18 | } 19 | 20 | /* a style like this should never apply in IE. If it does, tests will fail */ 21 | @media screen and (view-mode: minimized) { 22 | #testelem { 23 | width: 10px !important; 24 | } 25 | } 26 | 27 | /*styles for 480px and up - media type purposely left out here to test that in the process */ 28 | @media (min-width: 480px) { 29 | #testelem { 30 | width: 150px; 31 | } 32 | #testelem[class=foo] { 33 | height: 200px; 34 | } 35 | } 36 | 37 | /*styles for 500px and under*/ 38 | @media screen and (max-width: 460px) { 39 | #testelem { 40 | height: 150px; 41 | } 42 | } 43 | 44 | /* testing em unit support - 33em should be 528px and 35em should be 560px in IE with default font settings */ 45 | @media screen and (min-width: 33em) and (max-width: 38em) { 46 | #testelem { 47 | width: 75px; 48 | } 49 | } 50 | 51 | 52 | 53 | /*styles for 620px and up */ 54 | @media only screen and (min-width: 620px) { 55 | #testelem { 56 | width: 250px; 57 | } 58 | } 59 | 60 | 61 | /*styles for 760px and up */ 62 | @media only print, only screen and (min-width: 760px) { 63 | #testelem { 64 | width: 350px; 65 | } 66 | } 67 | 68 | 69 | /*styles for print that shouldn't apply */ 70 | @media only print and (min-width: 800px) { 71 | #testelem { 72 | width: 500px; 73 | } 74 | } -------------------------------------------------------------------------------- /test/unit/test2.css: -------------------------------------------------------------------------------- 1 | /* this stylesheet was referenced via a link that had a media attr defined 2 | it should only apply on window > 950px */ 3 | #testelem { 4 | width: 16px; 5 | } -------------------------------------------------------------------------------- /test/unit/test3.css: -------------------------------------------------------------------------------- 1 | /* this stylesheet was referenced via a link that had a media attr defined 2 | it should only apply on screen > 87.5em (1400px) */ 3 | #testelem { 4 | width: 25px; 5 | } -------------------------------------------------------------------------------- /test/unit/tests.js: -------------------------------------------------------------------------------- 1 | /* 2 | Respond.js unit tests - based on qUnit 3 | */ 4 | 5 | QUnit.config.reorder = false; 6 | 7 | window.onload = function(){ 8 | 9 | function getNormalizedUrl( filename ) { 10 | var url = window.location.href; 11 | return url.substr( 0, url.lastIndexOf( '/' ) + 1 ) + ( filename || '' ); 12 | } 13 | 14 | // ajax doesn’t finish if you queue them while respond is already ajaxing 15 | function queueRequest( callback ) { 16 | var clearQueue = window.setInterval( function() { 17 | if( !respond.queue.length ) { 18 | window.clearInterval( clearQueue ); 19 | callback(); 20 | } 21 | }, 50 ); 22 | } 23 | 24 | if( !window.opener ){ 25 | 26 | document.documentElement.className = "launcher"; 27 | 28 | document.getElementById("launcher").innerHTML = '

    Tests must run in a popup window. Open test suite

    '; 29 | 30 | document.getElementById( "suitelink" ).onclick = function(){ 31 | window.open( location.href + "?" + Math.random(), 'win', 'width=800,height=600,scrollbars=1,resizable=1' ); 32 | return false; 33 | }; 34 | 35 | } 36 | else { 37 | 38 | var testElem = document.getElementById("testelem"); 39 | 40 | function getWidth(){ 41 | return testElem.offsetWidth; 42 | } 43 | function getHeight(){ 44 | return testElem.offsetHeight; 45 | } 46 | 47 | // A short snippet for detecting versions of IE in JavaScript - author: @padolsey 48 | var ie = (function(){ 49 | 50 | var undef, 51 | v = 3, 52 | div = document.createElement('div'), 53 | all = div.getElementsByTagName('i'); 54 | 55 | while ( 56 | div.innerHTML = '', 57 | all[0] 58 | ); 59 | 60 | return v > 4 ? v : undef; 61 | 62 | }()); 63 | 64 | window.moveTo(0,0); 65 | 66 | /* TESTS HERE */ 67 | asyncTest( 'Styles not nested in media queries apply as expected', function() { 68 | window.resizeTo(200,800); 69 | setTimeout(function(){ 70 | strictEqual( getWidth(), 50, "testelem is 50px wide when window is 200px wide" ); 71 | start(); 72 | }, 900); 73 | }); 74 | 75 | asyncTest( 'styles within min-width media queries apply properly', function() { 76 | window.resizeTo(520,800); 77 | setTimeout(function(){ 78 | strictEqual( getWidth(), 150, 'testelem is 150px wide when window is 500px wide' ); 79 | start(); 80 | }, 900); 81 | }); 82 | 83 | // // This test is for a feature in IE7 and up 84 | if( ie >= 7 ){ 85 | asyncTest( "attribute selectors still work (where supported) after respond runs its course", function() { 86 | window.resizeTo(520,800); 87 | setTimeout(function(){ 88 | strictEqual( getHeight(), 200, "testelem is 200px tall when window is 500px wide" ); 89 | start(); 90 | }, 900); 91 | }); 92 | } 93 | 94 | 95 | asyncTest( 'styles within max-width media queries apply properly', function() { 96 | window.resizeTo(300,800); 97 | setTimeout(function(){ 98 | strictEqual( getHeight(), 150, 'testelem is 150px tall when window is under 480px wide' ); 99 | start(); 100 | }, 900); 101 | }); 102 | 103 | 104 | 105 | asyncTest( 'min and max-width media queries that use EM units apply properly', function() { 106 | window.resizeTo(580,800); 107 | setTimeout(function(){ 108 | strictEqual( getWidth(), 75, 'testelem is 75px wide when window is 580px wide (between 33em and 38em)' ); 109 | start(); 110 | }, 900); 111 | }); 112 | 113 | 114 | 115 | asyncTest( "styles within a min-width media query with an \"only\" keyword apply properly", function() { 116 | window.resizeTo(660,800); 117 | setTimeout(function(){ 118 | strictEqual( getWidth(), 250, "testelem is 250px wide when window is 650px wide" ); 119 | start(); 120 | }, 900); 121 | }); 122 | 123 | asyncTest( "styles within a media query with a one true query among other false queries apply properly", function() { 124 | window.resizeTo(800,800); 125 | setTimeout(function(){ 126 | strictEqual( getWidth(), 350, "testelem is 350px wide when window is > 620px wide" ); 127 | start(); 128 | }, 900); 129 | }); 130 | 131 | 132 | 133 | asyncTest( "Styles within a false media query do not apply", function() { 134 | window.resizeTo(800,800); 135 | setTimeout(function(){ 136 | notStrictEqual( getWidth(), 500, "testelem is not 500px wide when window is 800px wide" ); 137 | start(); 138 | 139 | }, 900); 140 | }); 141 | 142 | asyncTest( "stylesheets with a media query in a media attribute apply when they should", function() { 143 | window.resizeTo(1000,800); 144 | setTimeout(function(){ 145 | strictEqual( getWidth(), 16, "testelem is 16px wide when window is wider than 950px" ); 146 | start(); 147 | }, 900); 148 | }); 149 | 150 | // Careful, browserstack has a default resolution of 1024x768 151 | asyncTest( "stylesheets with an EM-based media query in a media attribute apply when they should", function() { 152 | window.resizeTo(1150,800); 153 | setTimeout(function(){ 154 | strictEqual( getWidth(), 25, "testelem is 25px wide when window is wider than 1100px wide. Does your screen width go that wide?" ); 155 | start(); 156 | }, 900); 157 | }); 158 | 159 | asyncTest( 'Test keyframe animation inside of media query', function() { 160 | queueRequest( function() { 161 | respond.ajax( getNormalizedUrl( 'test-with-keyframe.css' ), 162 | function( data ) { 163 | ok( data.replace( respond.regex.keyframes, '' ).match( respond.regex.media ), 'A keyframe animation doesn\'t bust the media regex.' ); 164 | start(); 165 | }); 166 | }); 167 | }); 168 | 169 | asyncTest( 'Test comments inside of a media query', function() { 170 | queueRequest( function() { 171 | respond.ajax( getNormalizedUrl( 'test-with-comment.css' ), 172 | function( data ) { 173 | var stripped = data.replace( respond.regex.comments, '' ); 174 | // TODO allow /* */ inside of CSS content strings. 175 | ok( stripped.match( respond.regex.media ), 'Comments don\'t bust the media regex.' ); 176 | ok( !stripped.match( /\/\*/gi ), 'No start comments exist in the result.' ); 177 | ok( !stripped.match( /\*\//gi ), 'No end comments exist in the result.' ); 178 | start(); 179 | }); 180 | }); 181 | }); 182 | 183 | test( 'Issue #242 overly agressive keyframes regex', function() { 184 | strictEqual( '@media(q1){ @keyframes abc{ from{ }to{ } } } @media(q2){}'.replace( respond.regex.keyframes, '' ), '@media(q1){ } @media(q2){}' ); 185 | strictEqual( '@media(q1){} @keyframes abc{ from{ }to{ } } @media(q2){}'.replace( respond.regex.keyframes, '' ), '@media(q1){} @media(q2){}' ); 186 | strictEqual( '@media(q1){} @media(q2){ @keyframes abc{ from{ }to{ } } }'.replace( respond.regex.keyframes, '' ), '@media(q1){} @media(q2){ }' ); 187 | }); 188 | 189 | test( 'Test spaces around min-width/max-width', function() { 190 | ok( '@media only screen and (min-width: 1px) { }'.match( respond.regex.maxw ) === null ); 191 | ok( '@media only screen and ( min-width: 1px ) { }'.match( respond.regex.maxw ) === null ); 192 | ok( '@media only screen and (min-width: 1px) { }'.match( respond.regex.minw ).length ); 193 | ok( '@media only screen and ( min-width: 1px ) { }'.match( respond.regex.minw ).length ); 194 | 195 | ok( '@media only screen and (max-width: 1280px) { }'.match( respond.regex.minw ) === null ); 196 | ok( '@media only screen and ( max-width: 1280px ) { }'.match( respond.regex.minw ) === null ); 197 | ok( '@media only screen and (max-width: 1280px) { }'.match( respond.regex.maxw ).length ); 198 | ok( '@media only screen and ( max-width: 1280px ) { }'.match( respond.regex.maxw ).length ); 199 | }); 200 | 201 | 202 | test( 'Issue #161: spaces around inside min-width/max-width', function() { 203 | ok( '@media only screen and (min-width : 1px) { }'.match( respond.regex.min ) !== null ); 204 | ok( '@media only screen and (max-width : 1px ) { }'.match( respond.regex.maxw ) !== null ); 205 | }); 206 | 207 | test( 'Issue #181: non-min-width and non-max-width queries', function() { 208 | var others = ['(min--moz-device-pixel-ratio: 1.5)', 209 | '(-moz-min-device-pixel-ratio: 1.5)', 210 | '(-o-min-device-pixel-ratio: 1.5)', 211 | '(-webkit-min-device-pixel-ratio: 1.5)', 212 | '(min-device-pixel-ratio: 1.5)', 213 | '(min-resolution: 1.5dppx)'], 214 | str, 215 | mq; 216 | 217 | for( var j = 0, k = others.length; j