RWSmith Designs.

Extraordinary Web Design

jQuery media queries how to do it, and why they are useful

First, let’s start with why we would want a media query to be executed in jQuery. Media queries are mostly used in responsive design to shift html elements. An example would be to break down all columns in a single column for the smallest screen sizes. They can also be used to test many other conditions but we won’t be going into those here.

Below is an example of some common CSS media queries, used typically in mobile first design:

One thing which is quite common is to display additional content on larger screen sizes. Obviously we cannot completely exclude our guests on smaller screens from this content, but due to their small screen it might be best to leave them a link to navigate to this content instead.

One way of doing this – the wrong way, but it is very common and something I myself was doing before I knew any better was placing that content in a wrapper and using display:none or positioning it off-screen.
Yes this does give the desired result – visually. But we are forcing those users on small screens, typically mobile devices with slow connections or limitations on bandwidth to download this additional content that is then not present for them to see.

Here is a better method: we can use jQuery to calculate the width of our screen and if a condition is met then serve up the additional content through Ajax. Nice.

Here’s how to do it:

First off you will want to grab the Enquire.js a javascript library that makes media queries in jQuery an absolute breeze.
Head on over to, download the minified code and add it to your JavaScript file.

Then it’s literally a matter of a few lines to serve some Ajaxed content if screen dimension conditions are met:

Where “blog / #main-article” is the path to the file containing the content and the id of the content container in that file.
So in this example if the screen width happens to exceed 700px the additional content is served up into the container with an id of “extra-content”. on the smaller screens the container would be empty and not visible to the user.

I am sure there are more efficient methods for Ajaxing the content, such as pulling directly from the database or having a seperate php file that grabs that data from the database and use ajax to pull in the php file.

Please feel free to share any other good uses for media queries in jQuery. by commenting below.


Leave a comment

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

RWSmith designs Extraordinary Web Design

Do you have a project in mind?

I’m currently available for freelance and accepting new project requests.

Contact meSee my process