Search
Close this search box.

Responsive Media Query using jQuery

Media query using jquery

Contents

Today we are going to look at media queries in jQuery. There is a fairly simple solution where most developers stuck once in a while. Before jumping in, lets take take a scenario that why you would ever use media queries through jQuery.

Scenario

I was working on client site where I had to get the browser height, assign height value to body tag, and then change page background color accordingly.

Solution

I used two functions only:

  1. if ( $(window).width() <= 767 ) { . . . }
    This is simply getting if width is lesser than equal 767 and then performing operation in curly braces. After that it uses else statement. Remember this statement will run when page will load.
  2. $(window).resize(function() { . . . } );
    Resize is used only when we resize the browser window. And then I copy/pasted the above if else statement inside the resize function. So that when window resizes it runs the media query again.

Here is a complete example solution.


jQuery(document).ready(function ($) {

   //for window size less than 767px
   if ( $(window).width() <= 767 ) { 
       $("div").css("background", "red");
   }
   //for window size greater than 767px
   if ( $(window).width() > 767 ) { 
       $("div").css("background", "blue");
   }

   // make sure if window is resized the code must work.
   $(window).resize(function() { 
         //for window size less than 767px
         if ( $(window).width() <= 767 ) { 
             $("div").css("background", "red");
         }
          //for window size greater than 767px
         if ( $(window).width() > 767 ) { 
             $("div").css("background", "blue");
         }
   });

});

Hope this tutorial helps you. Thanks.



Leave a Reply

Your email address will not be published. Required fields are marked *

Picture of Hafiz Faraz Mukhtar

Hafiz Faraz Mukhtar

Hafiz Faraz Mukhtar is an expert Web Developer, SEO specialist, and Graphic Designer. Hafiz Faraz is an expert in WordPress design and development. Hire on Upwork | Hire on Fiverr