forked from paulirish/matchMedia.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatchMedia.addListener.js
43 lines (39 loc) · 1.04 KB
/
matchMedia.addListener.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
/*! matchMedia() polyfill addListener/removeListener extension. Author & copyright (c) 2012: Scott Jehl. Dual MIT/BSD license */
(function(){
// monkeypatch unsupported addListener/removeListener with polling
if( !window.matchMedia( "" ).addListener ){
var oldMM = window.matchMedia;
window.matchMedia = function( q ){
var ret = oldMM( q ),
listeners = [],
last = false,
timer,
check = function(){
var list = oldMM( q );
if( list.matches && !last ){
for( var i =0, il = listeners.length; i< il; i++ ){
listeners[ i ].call( ret, list );
}
}
last = list.matches;
};
ret.addListener = function( cb ){
listeners.push( cb );
if( !timer ){
timer = setInterval( check, 1000 );
}
};
ret.removeListener = function( cb ){
for( var i =0, il = listeners.length; i< il; i++ ){
if( listeners[ i ] === cb ){
listeners.splice( i, 1 );
}
}
if( !listeners.length && timer ){
clearInterval( timer );
}
};
return ret;
};
}
}());