Platinum Partner
css,html5,javascript,css3,tips and tricks

Using Media Queries in JavaScript Code

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 {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}