Paulund
2014-06-06 #javascript

Checking Media Queries With Javascript

With the web being used on so many different devices now it's very important that you can change your design to fit on different screen sizes. The best way of changing your display depending on screen size is to use media queries to find out the size viewport of the screen and allowing you to change the design depending on what screen size is on. You will mainly make these changes in the CSS file as you can define the media query break points to change the design on different devices like this.


/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {

}

/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {

}

/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {

}

The above code will allow you to make styling completely different on different devices, but what if you wanted to change the functionality of the site depending on the screen size? What if you needed to use some Javascript code on different screen sizes, for example to create a slide down navigation button.

How Do You Use Media Queries With jQuery

Media queries will be checking the width of the window to see what the size of the device is so you would think that you can use a method like .width() on the window object like this.


if($(window).width() < 767)
{
   // change functionality for smaller screens
} else {
   // change functionality for larger screens
}

But this will not return the true value of the window as it takes into effect things like body padding and scroll bars on the window. The other option you have when checking the media size is to use a Javascript method of .matchMedia() on the window object.


var window_size = window.matchMedia('(max-width: 768px)'));

This works the same way as media queries and is supported on many browsers apart from IE9 and lower. Can I Use window.matchMedia To use matchMedia you need to pass in the min or max values you want to check (like media queries) and see if the viewport matches this.


if (window.matchMedia('(max-width: 768px)').matches)
{
    // do functionality on screens smaller than 768px
}

Now you can use this to add a click event on to a sub-menu for screens smaller than 768px. The below code is an example of how you can add some Javascript code which will only be run on screens smaller than 768px.


if (window.matchMedia('(max-width: 768px)').matches)
{
    $('.sub-menu-button').on('click', function(e)
    {
        var subMenu = $(this).next('.sub-navigation');
        if(subMenu.is(':visible'))
        {
            subMenu.slideUp();
        } else {
            subMenu.slideDown();
        }

        return false;
    });
}