|
1bba387
Scott Jehl authored
|
||
| 1 | /*! matchMedia() polyfill addListener/removeListener extension. Author & copyright (c) 2012: Scott Jehl. Dual MIT/BSD license */ | |
| 2 | (function(){ | |
| 3 | // monkeypatch unsupported addListener/removeListener with polling | |
|
d62f1d5
Scott Jehl authored
|
||
| 4 | if( !window.matchMedia( "all" ).addListener ){ | |
|
1bba387
Scott Jehl authored
|
||
| 5 | var oldMM = window.matchMedia; | |
| 6 | ||
| 7 | window.matchMedia = function( q ){ | |
| 8 | var ret = oldMM( q ), | |
| 9 | listeners = [], | |
|
812ffb0
WickyNilliams authored
|
||
| 10 | last = ret.matches, | |
|
1bba387
Scott Jehl authored
|
||
| 11 | timer, | |
| 12 | check = function(){ | |
|
70f13fc
WickyNilliams authored
|
||
| 13 | var list = oldMM( q ), | |
| 14 | unmatchToMatch = list.matches && !last, | |
| 15 | matchToUnmatch = !list.matches && last; | |
|
d003d45
WickyNilliams authored
|
||
| 16 | ||
| 17 | //fire callbacks only if transitioning to or from matched state | |
|
70f13fc
WickyNilliams authored
|
||
| 18 | if( unmatchToMatch || matchToUnmatch ){ | |
|
1bba387
Scott Jehl authored
|
||
| 19 | for( var i =0, il = listeners.length; i< il; i++ ){ | |
| 20 | listeners[ i ].call( ret, list ); | |
| 21 | } | |
| 22 | } | |
| 23 | last = list.matches; | |
| 24 | }; | |
| 25 | ||
| 26 | ret.addListener = function( cb ){ | |
| 27 | listeners.push( cb ); | |
| 28 | if( !timer ){ | |
| 29 | timer = setInterval( check, 1000 ); | |
| 30 | } | |
| 31 | }; | |
| 32 | ||
| 33 | ret.removeListener = function( cb ){ | |
| 34 | for( var i =0, il = listeners.length; i< il; i++ ){ | |
| 35 | if( listeners[ i ] === cb ){ | |
| 36 | listeners.splice( i, 1 ); | |
| 37 | } | |
| 38 | } | |
| 39 | if( !listeners.length && timer ){ | |
| 40 | clearInterval( timer ); | |
| 41 | } | |
| 42 | }; | |
| 43 | ||
| 44 | return ret; | |
| 45 | }; | |
| 46 | } | |
|
d003d45
WickyNilliams authored
|
||
| 47 | }()); |