Detect media queries with Javascript

Detect if CSS media queries are met or not, using Javascript programming.

The , which allow us to detect different characteristics of the devices to apply some styles or others depending on them, are well known.

Surely we use them intensively in our developments, but from CSS. In this article we will see how we can do it from Javascript. It is a very easy practice, which uses a Javascript API that is fully supported by browsers, as we can see in the following image:

Why detect media queries from Javascript?

It is less usual that from Javascript we need to detect if certain media queries are being evaluated positively, but we can also find ourselves in need of it. There are times when certain mechanisms are only necessary when we are viewing the page on a computer with a large screen, but not on a mobile or tablet

Let’s say, for example, that we have a code for a banner that we only want to see on desktop computers. This code makes asynchronous calls to request the creative from the banner server, but if the banner isn’t going to display, what’s the point of making those calls to the banner server?

If the banner always appears on the page and we simply hide and show it with CSS, then even if it doesn’t show up on mobile screens, it would still be requesting the banner and wasting unnecessary bandwidth. Instead, we can simply detect with Javascript when we’re on a desktop, to dynamically place the banner code only then.

It is one example among many that can occur to us. By one or the other, the needs to detect mediaqueries will arrive. I’m not going to wind up more to be able to move on to practice.

matchMedia method to test media queries

The method that we are going to use to be able to check if a media query is fulfilled is called matchMedia(). It’s inside the “window” object.

var mediaqueryList = window.matchMedia(“(min-width: 500px)”);

The matchMedia() method returns a “mediaquery list” object. It basically tells you about the mediaquery that has been checked and its value.

If we want to see if this media query is true at a given time, we simply have to evaluate the “matches” property of this object.

if(mediaqueryList.matches) { alert(‘The media query is met’); }

That “mediaqueryList” object is dynamic, in the sense that if browser conditions change over time, the “matches” property will also change. Therefore, it could happen that this evaluation has different results at different times, if for example the user resizes the browser window.

Define an event handler to handle changes in the evaluation of media queries

The most likely thing is that in your application you want to be aware of the changes in the media queries that you are evaluating with Javascript, to take action when this happens.

Sure, you could constantly ask for the value of the “matches” property, but the most efficient thing is to associate an event handler to perform actions just when that media query changes value.

We do this with the “addListener” method of the mediaqueryList object, as shown below.

var mediaqueryList = window.matchMedia(“(max-width: 920px)”); mediaqueryList.addListener( function(MediaQueryListEvent) { console.log(‘Listener executed’, MediaQueryListEvent); });

In this case we have associated an anonymous function as event handler. In this function we receive an object of the “MediaQueryListEvent” type, which offers us detailed information about the event that has occurred.

Checking whether or not the media query is fulfilled after that event is as simple as re-evaluating its “matches” property, using in this case the event object itself that we are receiving as a parameter in the browser.

var mediaqueryList = window.matchMedia(“(orientation: portrait)”); mediaqueryList.addListener( function(MediaQueryListEvent) { if(MediaQueryListEvent.matches) { // We perform the actions when the state of the mediaquery changes and now it meets its value alert(‘You have now switched to portrait mode, with your screen oriented vertically’ ); } else { alert(‘You are now in landscape mode, with your screen oriented horizontally’); } });

You can remove the event handler at any time, with the removeListener() method. Only to use it you can’t have associated the handler with an anonymous function as we have done before.

The code would look more or less like the following:

var mediaqueryList = window.matchMedia(“(orientation: portrait)”); function handler(MediaQueryListEvent) { if(MediaQueryListEvent.matches) { alert(‘The media query is now met’); } else { alert(‘The media query is no longer met’); } } // attach the event handler mediaqueryList.addListener(handler); // remove the event handler to stop receiving change notification mediaqueryList.removeListener(handler);

conclusion

With this we have learned to handle the state of the media queries in a programmatic way, that is to say, through code that will be executed through Javascript in the browser.

It is not a practice that is needed every day or in all projects, but there will come a day when it will be useful to you. Because of its broad, widespread support, you can make use of what you’ve learned on any website where you need to keep an eye out for media query changes and perform Javascript actions when they occur.

Remember that you can see many other practices to make designs adaptable to the conditions of the browser in the

See also  FOR EACH loop
Loading Facebook Comments ...
Loading Disqus Comments ...