-
Notifications
You must be signed in to change notification settings - Fork 0
/
matchMedia.js
79 lines (59 loc) · 2.54 KB
/
matchMedia.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
window.matchMedia = window.matchMedia || (function(doc, undefined){
var docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement('body'),
div = doc.createElement('div');
div.id = 'mq-test-1';
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
var mqRun = function ( mq ) {
div.innerHTML = '­<style media="' + mq + '"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore( fakeBody, refNode );
bool = div.offsetWidth === 42;
docElem.removeChild( fakeBody );
return { matches: bool, media: mq };
},
getEmValue = function () {
var ret,
body = docElem.body,
fakeUsed = false;
div.style.cssText = "position:absolute;font-size:1em;width:1em";
if( !body ) {
body = fakeUsed = doc.createElement( "body" );
body.style.background = "none";
}
body.appendChild( div );
docElem.insertBefore( body, docElem.firstChild );
if( fakeUsed ) {
docElem.removeChild( body );
} else {
body.removeChild( div );
}
//also update eminpx before returning
ret = eminpx = parseFloat( div.offsetWidth );
return ret;
},
//cached container for 1em value, populated the first time it's needed
eminpx,
// verify that we have support for a simple media query
mqSupport = mqRun( '(min-width: 0px)' ).matches;
return function ( mq ) {
if( mqSupport ) {
return mqRun( mq );
} else {
var min = mq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
max = mq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
minnull = min === null,
maxnull = max === null,
currWidth = doc.body.offsetWidth,
em = 'em';
if( !!min ) { min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); }
if( !!max ) { max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); }
bool = ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max );
return { matches: bool, media: mq };
}
};
}( document ));