HTML5 Zone is brought to you in partnership with:

Gil Fink, Microsoft MVP, is an expert in Web development and Microsoft data platform. He works as a senior architect at Sela Group. He is currently consulting for various enterprises and companies, where he architects and develops Web and RIA-based solutions. He conducts lectures and workshops for developers and enterprises who want to specialize in infrastructure and Web development. He is also a co-author of several Microsoft Official Courses and training kits. You can read his publications at his blog: http://blogs.microsoft.co.il/blogs/gilf. Gil is a DZone MVB and is not an employee of DZone and has posted 151 posts at DZone. You can read more from them at their website. View Full User Profile

Using Media Queries in JavaScript Code

12.10.2012
| 5030 views |
  • submit to reddit

Using Media Queries in JavaScriptOne of the great additions in CSS3 is the ability to use media queries. Media queries are queries written in CSS which enables you to check different medias types like screen, resolution, print and more. After the query check, you will be able to impose CSS as response for the media that was checked. This behavior occurs automatically but what if you want to check media and impose some logic that isn’t necessary related to style or responsive design? The answer will be discussed in this post.

Pay attention the API written in this post is in draft state and it might change in the future.

Using Media Queries in JavaScript

So you want to use media queries in your JavaScript code.

The first thing to know is the new MediaQueryList object. The MediaQueryList object is a list of all the media queries on the document object. The MediaQueryList object sends notifications to registered listeners when a media queries on a document change their state. The MediaQueryList object includes two functions which add and remove listeners: addListener and removeListener. Here is an example of adding an event listener:

mql.addListener(handleScreenChange);

It also includes two properties:

  • matches: returns true if the document match the media query list, otherwise false.
  • media: the media query list stored in the MediaQueryList object.

In order to obtain a MediaQueryList object you need to use the matchMedia function. The matchMedia function receives a media query string and returns a MediaQueryList object. Then, you can use the matches property to check the result of the query or add event listeners to handle media queries changes. The following example shows a script that is used to write to the console screen changes:

(function () {           
    function resize() {
        if (window.matchMedia('only screen and (max-width: 320px)').matches) {
            console.log('under 320 pixels');                    
        } else if (window.matchMedia('only screen and (min-width: 321px) and ' +
                                     '(max-width: 1024px)').matches) {
            console.log('between 320 and 1024 pixels');                    
        } else {
            console.log('higher than 1024 pixels');                    
        }
    }
 
    window.addEventListener('resize', resize, false);
    resize();
}());

In the example, I’m registering to the window resize event. When a window resize happens, a check against the different media queries occurs and the relevant message is written to the console. You can avoid the registration to the resize event if you add a listener to the media query list:

(function () {
            function resize() {
                var mql = window.matchMedia('only screen and (max-width: 320px)').addListener(function () {
                    console.log('under 320 pixels');
                });
                var mql1 = window.matchMedia('only screen and (min-width: 321px) and ' +
                                             '(max-width: 1024px)').addListener(function () {
                                                 console.log('between 320 and 1024 pixels');
                                             });
                var mql2 = window.matchMedia('only screen and (min-width: 1025px)').addListener(function () {
                    console.log('higher than 1024 pixels');
                });
            }
            
            resize();
        }());

Pay attention to use the removeListener when you don’t need to get notifications when media query checks occur.

The support for the media query JavaScript API is available from Chrome version 9, Firefox version 6, IE10, and Safari version 5.1. Opera doesn’t support this API currently.

Summary

Media queries help to support responsive design that reacts to different media. When you want to use media queries from JavaScript you can use the MediaQueryList object and the matchMedia function.



Published at DZone with permission of Gil Fink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)