Skip to content

Instantly share code, notes, and snippets.

@abberg
Last active June 13, 2017 02:29
Show Gist options
  • Save abberg/d2703762bb8c7ee20c036fb106b83a3e to your computer and use it in GitHub Desktop.
Save abberg/d2703762bb8c7ee20c036fb106b83a3e to your computer and use it in GitHub Desktop.
get media queries from stylesheets and dispatch events when the change
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