Last active
June 13, 2017 02:29
-
-
Save abberg/d2703762bb8c7ee20c036fb106b83a3e to your computer and use it in GitHub Desktop.
get media queries from stylesheets and dispatch events when the change
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var styleSheets = Array.from(document.styleSheets); | |
var cssRules = styleSheets.filter(function(styleSheet){ | |
// cross domain stylesheets without a policy file will return false | |
return styleSheet.rules; | |
}).map(function(styleSheet){ | |
var rules = Array.from(styleSheet.rules); | |
return rules.filter(function(rule){ | |
// extract only the media query rules | |
return rule.type === CSSRule.MEDIA_RULE; | |
}) | |
}).reduce(function(rules){ | |
return rules; | |
}); | |
if(cssRules){ | |
cssRules.forEach(function(rule){ | |
var mediaQueryList = window.matchMedia(rule.conditionText); | |
mediaQueryList.addEventListener('change', function(event){ | |
window.dispatchEvent(new CustomEvent('mediaquerychange', { 'detail': {media: event.media, matches:event.matches} })) | |
}) | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment