List all media page requests in a list

Using JavaScript, what would be the best way to display a list containing all the media queries that apply to the current page.

I assume that this will be necessary for filtering in order to find the embedded media queries, i.e.

<link rel="stylesheet" media="only screen and (min-width: 30em)" href="/css/30em.css">

as well as media queries located in CSS files, i.e.

@media only screen and (min-width: 320px) {}

An example of the output of what I'm looking for:

 <p>There are 3 media queries loaded on this page</p> <ol> <li>30em</li> <li>40em</li> <li>960px</li> </ol> 
+8
javascript jquery responsive-design media-queries
source share
3 answers

Check here with the code for displaying media queries that apply to the current page

JavaScript:

 var mediaQueryCount = 0; $(document).ready(function(){ $links = $('link[rel="stylesheet"]'); $.each($links, function(i, item){ if(item.media){ mediaQueryCount++; var start = item.media.indexOf('(')+1; var end = item.media.indexOf(')'); var str = item.media.substring(start, end); var listItem = $('<li />',{ html: str.split(':')[1] }).appendTo("#result"); } }); $('#totalMedia').text(mediaQueryCount); }); 

HTML:

 <!DOCTYPE html> <html> <head> <link rel="stylesheet" media="only screen and (min-width: 30em)" /> <link rel="stylesheet" media="only screen and (min-width: 40em)"/> <link rel="stylesheet" media="only screen and (min-width: 960px)"/> </head> <body> <p>There are <span id="totalMedia"></span> media queries loaded on this page</p> <ol id="result"> </ol> </body> </html> 
+4
source share

You can use the MediaQueryList object:

The MediaQueryList object maintains a list of media queries in a document and processes the sending of notifications to listeners when media queries in a document change.

Related article by Nicholas K. Zakas:

http://www.nczonline.net/blog/2012/01/03/css-media-queries-in-javascript-part-1/


Another option is to use the styleSheets property of the document object.

 var $ol = $('<ol/>'); var styleSheet = document.styleSheets; $.each(styleSheet, function(i, styleObject) { $.each(styleObject.cssRules, function(i, rule){ if (rule.media) { $ol.append(rule.media[0]) // only screen and (min-width: 481px) and (max-width: 768px) } }) }) var len = $ol.find('li').length; $('p').text('There are ' + len + ' media queries loaded on this page') $('body').append($ol) 
+7
source share

Check out this link. I used the @sureshunivers code to parse and create a li list.

 var sheets = document.styleSheets; //contains an object of all loaded stylesheets var rules = sheets[i].cssRules; //The rules variable is list of all the rules of the current stylesheet represented as CSSRule objects. 

Make this article Responsive to Media Requests in javascript

+1
source share

All Articles