One 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.
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:
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:
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:
Pay attention to use the removeListener when you don’t need to get notifications when media query checks occur.