Back to All

Firing Responsive jQuery Functions based on CSS Media Queries Rather than Window Width


There are some great options for managing Javascript when using CSS media queries in a responsive website. MediaCheck, jRespond, and Breakpoints.js all allow you to fire javascript functions based on customizable breakpoints in browser width. However, recently I was working on a small site with only a single function to be called at a smaller browser size, in conjunction with a media query, and thought I'd forgo one of these scripts and manage my change using a jQuery window width measurement.

The Problem: jQuery $(window).width() and CSS3 Media Queries do not always match.

Initially I was using the below code:

	if ($(window).width() <= 800){	
		// do something here

When viewing the site in Firefox, I noticed a small difference in the width at which my media query and javascript were firing. Roger Johansson recently wrote up a great article documenting the inconsistent treatment of vertical scrollbars in media query widths. This inconsistency causes a small difference between browsers in the actual window width when a media query fires, which in turn causes media query and jQuery width measurements to not match in some popular browsers: Firefox, IE, and Opera. Here is a code example showing the difference between the jQuery window width and the media query width measurement.

The solution: use jQuery to test for a changed CSS property, rather than the browser width

Rather than the measuring the screen width on resize of the window, I check for a css rule that is changed by the media query. This way, regardless of the how the browser treats the scrollbar, the media query will fire at the same time.

Suppose the "sampleClass" class has a float:left rule before the media query, and a float:none rule after, on window resize I check for the change in that rule. We also need to test the css class on initial load of the page.

The jQuery

$(document).ready(function() {
    // run test on initial page load

    // run test on resize of the window

//Function to the css rule
function checkSize(){
    if ($(".sampleClass").css("float") == "none" ){
        // your code here


.sampleClass {float:left;}
@media only screen and (max-width: 800px){
	.sampleClass {float:none;}

Was this article helpful?


Vinod Patil

It’s great, thank you ! :)


Thank you! This sounds exactly what I have been looking for. By the way, I love the way your site here responds by making the navigation menu animate when the width is smaller. I might just use that for my site. Thanks for the inspiration and keep up the good work!

Anthony Cullen

Worked a treat targeting z-index of a relatively-positioned element. Thanks!


Smart and clean move. I’m going to use it with Bootstrap by checking .container’s width. Thanks for sharing.


Awesome!! Thx dude ;)


Perfect !
jquery has ever the answer ;)

Alan A

What a great idea! Using it right now.


That’s neat a way to go about things, I’ve got some media queries/scripts to galvanize!  Thanks for the tip!


This is bad because it intrinsically links behaviour (JS) to content (HTML). Say you (or a colleague) may in the future need to remove the JS hook element (the floated left class). Doing so would render this JS function obsolete (unused code), and would furthermore interfere with the intentional behaviour of the responsive design. We should always be mindful to keep a ‘separation of concerns’ when it comes to these sorts of problems.

Chris Arasin

Hi Fergus, good point. My counter argument for this method is that in many cases, we may want that intrinsic link between the javascript and the markup. For example, if there’s a piece of content that at larger screen sizes functions as a slideshow but then at smaller sizes breaks out of the slideshow into a scrollable format, you would want the javascript to change exactly when the css modifies the layout.

But to your point, yes a totally arbitrary selection of css rule to check against may lead to a problem down the road.


That intrinsic link can (and I think should) be communicated through employing semantically similar JS hooks and CSS classes/IDs. For instance, I might have some buttons with class=“random_button”. If I want to attach JS behaviour to those buttons I would add an additional class of ‘js_random_button’. Decoupling of behaviour and presentation, as you say, prevents problems later on, but it also serves as a helpful visual indicator of intent. Given that class, it will be immediately obvious to others that the element/s is/are also used in a JS script. There are many advantages to this type of css selector allocation.


What a clever, elegant solution. Thanks!


Yes.. but happens when you initially load the page on a mobile device, so there’s no actual browser resize happening? Then this jQuery never fires.

Chris Arasin

You can do a check outside of the window.resize function as well.

Ünsal Korkmaz

Seriously i love those type of solutions ^^ Thank you

Dagobert Renouf

Superb idea, I love how it makes it basically impossible to fail, and as it’s supposed to be linked to the css anyway… this is perfect, thank you so much for posting this!

Bill Criswell

Awesome idea. I think you guys would find Jeremy Keith’s approach very interesting as well. I hacked up a little example for you.


Thanks! This was a big help.


Why not just give ‘html’ a width of 100% on your stylesheet and use jQuery to pull the width. Another bonus of doing that is it will account for the width of the scroll bar. Just a thought…

Working example:

Chris Arasin

Thanks Justin, I like that method too.

Shaun W.


Using bootstrap.

Set a display: hidden; div with a .responsiveTell class then set content: ‘xs’; in each media query

Then tested for .css(‘content’) === ‘xs/sm/md/lg’ in jquery

Frank Folsche

Hey, nice script but there where a few things not working for me:
like Chris Arasin mentioned you also need to check outside of the resize function otherwise the function does not get called on mobile divices. (tip: you can check this easily in chrome canary)
also the resize function checks for both vertical and horizontal changes, and you only need to detect the horizontal change, this was a problem for me because I was changing the height of the window and the function kept on firing.
I’m now using this:
$(document).ready(function () {
  $(window).resize(function () {
      if ($(window).height() == height) return;
function mobile() {
  if ($(“body”).css(“left”) == “3px”) {//mobile test == <500


Doesn’t work for me unfortunately, using html5 boilerplate with jQuery 1.10.2 ... without the line “if ($(”.sampleClass”).css(“float”) == “none” ){” my code fires up no problems, though. is there any special requirement for this function to work? this is my full code:
      if ($(“p.test”).css(“font-size” == “3em” ){
          $(“body”).click(function() {


Anyone got any thoughts on what a good CSS property to be applied to the body that wouldn’t go anything? That way that property wont need to be overridden if the site is restyled, and the body (unlike other elements) will always be on the page.

Umair Hafeez

Great :-) works like a charm…

Gunnar Bittersmann

This has little to do with jQuery. You can easily do the same in vanilla JavaScript.


@Pawel, you have a little mistake right here:

  if ($(“p.test”).css(“font-size” == “3em” ){

Notice the == operator is inside the .css() method parentheses. What happens here is instead of first acquiring the font size and then comparing it with “3em”, your code instead compares the literal string “font-size” with “3em”, then essentially calls $(“p.test”).css(false). Oh, and it appear you lost a close-paren for the if condition somewhere along the way :) So, here’s how that line should look like:

  if ($(“p.test”).css (“font-size”) == “3em”) {

Yudhistira Mauris

Very smart move, I didn’t even think about that. What is the thing that causes the difference between CSS3 media query and jQuery width()? Is it a browser bug?

Chris Arasin

Hi Yudhistira,
It had to do with how browsers were handling the scroll bar on a page when measuring the width. Looking back at the example now, it’s looking like maybe new browsers have corrected this and made the measurement consistent.

Eric D. Greene

Simple and elegant solution, I like it.


Much cleaner then constantly using js to do millions off if statements as the window is resized wow good job.

Stephen T

This is slick. I set my conditionals for both document ready AND window resize. Minimize the liability of the depency on an attribute value by having the script look at something really consistent, like a mobile/desktop menu.

      // enable and close when resizing to mobile…
if ($(“header nav.desktop”).css(“display”) == “none” ){
  $( “.accordion” ).accordion({
  collapsible: true,
  active: false,
  disabled: false

// ... or open and disable when resizing to tablet/desktop
else if ($(“header nav.desktop”).css(“display”) == “block” ){
  $( “.accordion” ).accordion({
  collapsible: false,
  disabled: true


yo. thanks for this, loving it. made a css element with css content and let it fire only once it changes:
#responsive { content:“XS”; display:none;}

@media screen and (min-width: 450px) {
#responsive {content:“S”;}

@media screen and (min-width: 600px) {
#responsive {content:“M”;}

@media screen and (min-width: 960px) {
#responsive {content:“L”;}
var responsiveValue, responsiveChange;
(responsiveChange = function() {
if ( $(”#responsive”).css(“content”) !== responsiveValue ) {
  if ( $(”#responsive”).css(“content”) === ‘“L”’ ) {
  console.log( “HEY! ITS LARGE” );
  //do stuff only @ large..
  } else {
  console.log( $(”#responsive”).css(“content”) );
  // else…
  responsiveValue = $(”#responsive”).css(“content”);
$(window).resize( function() {

dont forget to place an element with id responsive to your DOM. thanks!!!

Chris Arasin

Nice. You’re probably also going to want to fire responsiveChange() on document as well.

Dave Amphlett

Genius. Thanks for sharing - probably saved me hours of messing around.

D Man

resize does not fire if the site was initially checked from a mobile device? thus anything inside the resize function never fires?

Chris Arasin

Hey D Man, run your check on document.load as well.


yo are right chris. i forgot to wrap it all into a ready state for this example. please feel free to edit my comment so it might help anybody in need. once again, it works perfectly for me so: thanks.


Thanks for this fix, exactly what I needed to solve the browser issues!! Wouldn’t have thought of this simple solution :)


Why not just use innerwidth? It’s less expensive to your application than detecting a property in your css


This is great and working, but only when resizing window - it doesn’t work if the page is opened in particular size. How to fix this?

Chris Arasin

Hi Kate, also run the conditional check on document.ready. I’m going to update the code sample.


That’s the trick!
Thank you!


check this code when we resize the browser aplying so many list tags
<!DOCTYPE html>

if ($(window).width() <= 767){
  $(“ul li:nth-child(2n+2)”).append(”<li></li>”);
} else {
  $(“ul li:nth-child(3n+3)”).append(”<li></li>”);


  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>



How clever! Thank you for this.

Daniele Mancino

Re: James “Anyone got any thoughts on what a good CSS property to be applied to the body that wouldn’t go anything? That way that property wont need to be overridden if the site is restyled, and the body (unlike other elements) will always be on the page.”

Not to the body itself, but while implementing this (great!) solution to my Bootstrap/WordPress template I found that the most unobtrusive way is to add an extra class to the main div wrapper (also in every page) and change its background-color so that can be either white (also the background color of body) or transparent (which won’t change anything). This way:


body {
background-color: #fff;

.checksize {
background-color: transparent;

@media (min-width:991px){
.checksize {
background-color: #fff;


<div id=“page” class=“blah1 blah2 checksize”>


How about window.matchMedia()?

It doesn’t work in IE9 or earlier so you should use it so it degrades gracefully.


Do you not think it would better to throttle or debounce the resize event?


Hmm… nice idea but not convinced. David Walsh posted something similar a while ago:

It’d much better to use the content of pseudoelements like here for example. Also please debounce the resize event. Another better solution would be to use enquire.js if you do not need to support old browsers which uses window.matchMedia.

Mahesh Waghmare

Nice trick.

Patrick Hawley

I number my breakpoints, and the add a #breakpoint element (or call it whatever) to the DOM, and then set the z-index to the current breakpoint in my Sass. This allows me to determine the current breakpoint in JS.

Reinier Kaper

Modernizr has an .mq method that tests against an actual media query, might be a nice solution for people using Modernizr (which you probably should).


The problem with this code is that it will fire many times, not only when you cross the media query boundary, even a 1px change will fire the function and that’s not what you want. You have to store the state in some variable and avoid firing your function unless the resize really crossed the boundary you are watching for.

Angela Holden

This worked perfectly. Thank you!

Alexander Holman

A friend and I made this solution a few months ago: requires jQuery though.

Hope it helps someone, otherwise I guess we wasted our time :S


Thanks for this snippet. Was looking for a fix and this is perfect!


Thank you so much.


Hi, i want to know how can i use this to make my menu responsive. Thanks

Joran Schneyer

My solution was to insert two invisible div element into the html code. One for max values and one for min values.
Then I changed the title based on screen sizes like for the first one (max-width: 768px) the title “maxXs” or for the second one (min-width: 992px) the title “minSm”.
In javascript I can refer to the title everytime I want to know if my page is displayed on a phone (xs), a tablet (sm) or a desktop (md) and (lg).

Joran Schneyer

My solution was to insert two invisible div element into the html code. One for max values and one for min values.
Then I changed the content based on screen sizes like for the first one (max-width: 768px) the title “maxXs” or for the second one (min-width: 992px) the title “minSm”.
In javascript I can refer to the title everytime I want to know if my page is displayed on a phone (xs), a tablet (sm) or a desktop (md) and (lg).

Joe N.

Nice trick. Just what I needed to solve the “breakpoint problem.” Good thinking!


hi my name is amit moreal and i want to add a media query in this script
$(document).ready(function() {
  speedDown: 300,
  speedUp: 300,
  height: ‘380px’,
  showText: ‘Show more’,
  hideText: ‘Show less’

please help me


Niiiiice.. you just saved me 3 hours

Bilal Korir

Ammmm! this is a smart idea, though I haven’t tested yet but I really like it!



Wilbur Wright

Brilliant solution, best I have found online yet. Simple and direct.


Thank’s alot. this is really great!

Like this you can make it work with Bootstrap media-queries:

function checkSize(){
    if (jQuery('.visible-xs').css('display') === 'block') {
        //this is XS breakpoint

just change the class to any Bootstrap breakpoint (visible-xs, visible-sm, visible-md, visible-lg) and you can trigger any of them.

if you need more then one breakpoint combined you can simply do like so:

function checkSize(){
    if (jQuery('.visible-xs').css('display') || jQuery('.visible-md').css('display') === 'block') {
        //this is XS or MD breakpoint

I hope this helps someboy :)

Add a Comment

* Required Fields
background background
background background background
background background background background