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:
- 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. - $(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.