Media query using jquery

Responsive Media Query using jQuery

In CSS, JS, Wordpress by Hafiz Faraz MukhtarLeave a Comment

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.

Hope this tutorial helps you. Thanks.

About the Author
Hafiz Faraz Mukhtar

Hafiz Faraz Mukhtar

Facebook Twitter

Hafiz Faraz Mukhtar is an expert Web Developer, SEO specialist, and Graphic Designer. Hafiz Faraz is an expert in WordPress design and development. If you would like to hire him, here is his Upwork profile link: https://www.upwork.com/fl/hfarazm

Leave a Comment