How to Use Media Queries with jQuery

The evolution of smartphones and tablets has forced website owners to integrate mobile/tablet friendly (or responsive design) techniques. The creation of responsive design websites has subsequently evolved with new tools and frameworks. Media queries play an important role to create a responsive design as it allows content rendering to adapt to conditions such as screen resolution (e.g. smartphone screen vs. computer screen). Media query is a CSS module which was introduced with CSS3. But, did you know it can still be used with jQuery? It can! Let's learn more about media queries and how you can implement them with jQuery.

What are media queries?

Before we look at jQuery, here is a brief introduction about media queries. CSS Media queries allow you to target CSS rules based on - for instance - screen size, device-orientation or display-density. This means you can use CSS Media Queries to tweak CSS for an iPad, printer or create a responsive site. It uses the @media rule to include a block of CSS properties only if a certain condition is true.
As an example, if the browser window is smaller than 300px, the background color will change to yellow:

@media only screen and (max-width: 300px) {
     body {
         background-color: yellow;

The above is a pretty familiar piece of CSS3 code for handling screen sizes. Media queries can handle the responsive UI design pretty well, but what if you want to change some of the functions of the site based on screen size? What if you need to use different code blocks or JS functions based on different screen sizes? In a case like this, you'll need a way to run these media queries via jQuery. Unfortunately, at this point there are no solid predefined methods which provide actual information about screen size. Therefore, you'll need to use a third party library named Modernizr with jQuery in order to implement media queries.

What is Modernizr 

Modernizr is a JavaScript library which is designed to detect HTML5 and CSS3 features in various browsers, which lets JavaScript avoid using unimplemented features or use a workaround such as a shim to emulate them. Modernizr aims to provide this feature detection in a complete and standardized manner.
According to the official site, "Modernizr is a small piece of JavaScript code that automatically detects the availability of next-generation web technologies in your user's browser. Rather than blacklisting entire ranges of browsers based on “UA sniffing,” Modernizr uses feature detection to allow you to easily tailor your user's experiences based on the actual capabilities of their browser."
In other words, it detects browser features to find out if things are supported or not. It tells you what HTML, CSS and JavaScript features the user’s browser has to offer.
Let’s see an example of the program in action. Imagine if you wanted to detect whether an audio feature introduced with HTML 5 is supported by the browser...

How to use Modernizr? 

First, download the Modernizr library from the download page. Select the features which are required for your project and select “Build.” This will ensure that you no longer need to include features which you may not use, and it reduces the library file size also. Once downloaded, include the reference in your page:

<script src="modernizr.js" type="text/javascript"></script>
And then in your JavaScript code, you can check it like this:
if ( {
   /* Audio supported */
/* Audio not supported */

Simple and easy. Now let’s see how modernizer can help when jQuery allows the use of media queries!

 How to use media queries with jQuery

Before we get into Modernizer with jQuery, you may want to think about using the inbuilt width() function which returns the width of any matched element. This can be used with $(window) object to get its width like this:

if($(window).width() < 481)
{    // It’s a Phone.}
elseif($(window).width() < 769)
{    // It’s a tablet.}
else { // It’s a desktop/laptop.}

But, the issue with the width() function is that it doesn’t return the correct value of the window as it takes into effect things like body padding and scroll bars on the window. Therefore, we need Modernizer in order to get the correct information about the screen size.
Modernizer has lots of API to play with, one of which is allows you to systematically check if the current browser window state matches a media query. Following JavaScript function returns the device type based on the screen size via running min-width media query.

var checkMod = function() {  
        if ('(min-width: 480px)')) {   
            return 'phone';  
        else if ('(min-width: 768px)')) {   
            return 'tablet';  
        else {   
            return 'desktop;  

Then you can call this function on the initial load, as well as the window resize event:

$(document).ready()(function() {    // Call on every window resize  
    $(window).resize(checkMod);    // Call once on initial load   

Remember, only calling this function on page load will not work when the window is resized. Therefore, you must call for it in both places (page load and window resize.)
Also remember only valid media queries will be supported, therefore you should always include the value with media query with ‘px’ suffixed to it.  For example,'max-width: 640px') //Valid'max-width: 640') //Invalid'max-width') //Invalid

This way, you can also use media queries with jQuery.
What if browser doesn’t support media queries? You can use modernizer to detect the same, like this:

if('only all')) {
 // returns true if MQ are supported, false if not

Or you can use the following test:

Modernizr.addTest("cssmq", function(){
   return !!"only all");

The most common way of creating your own feature detects is by calling Modernizr.addTest with a string (preferably just lowercase, without any punctuation), and a function you want to execute that will return a boolean result.
That’s it!
To conclude, CSS3 media queries help in handling different UI based on size and orientation. But sometimes we need to execute different code blocks based on the screen size and none of the inbuilt jQuery methods give correct details about this factor. Hence, a third party library called Modernizr comes to the rescue in this case. Modernizr is the most popular library for creating a responsive website design. It can help to run media queries with jQuery to handle responsive design and it can also detect whether media queries are supported by the browser.

Responsive Menu
Add more content here...