Atadj Atadj - 2 months ago 8
CSS Question

jQuery window width not equal to CSS's window width

I'm using the following two pieces of CSS and JS code:

@media (max-width: 720px) {
// a code to make arrows in a carousel disappear
}

if(jQuery(window).width() <= 720){
// a code to make arrows in the carousel stop working
}


The problem with them is that the latter executes on exactly width=738px and not 720px. I suspect that this is because of browser's vertical scrollbar that has width equal to 18px in Chrome.

Is there a way to unify this? I'd like these actions to happen at the same moment in all browsers regardless of the scrollbar's width.

Tests (when browser is @ 720px and CSS has already executed):

jQuery(document).innerWidth() = 703
jQuery(window).innerWidth() = 703
jQuery(document).width() = 703
jQuery(window).width() = 703
jQuery('body').width() = 703
jQuery('html').width() = 703

Answer

I had to tackle the same problem a while ago, and so far the most correct solution I found is to use media queries to pass the actual window size to Javascript. You have to follow these steps:

  • Add a hidden element to your page,
  • Use media queries to alter the max-width property of that element,
  • Read back the max-width property of that element through Javascript.

For instance, add the following element to your page:

<div id="currentMedia"></div>

Then write the following CSS rules:

#currentMedia {
    display: none;
}

@media (max-width: 720px) {
    /* Make arrows in the carousel disappear... */

    #currentMedia {
        max-width: 720px;
    }
}

Then, from the Javascript side, you can write:

if (parseInt(jQuery("#currentMedia").css("max-width"), 10) <= 720) {
    // Make arrows in the carousel stop working...
}

And it will be accurate regardless of the scrollbar size, since the value comes from the same media query that triggers the carousel's disappearance.

I tested this solution on all major recent browsers, and it gives correct results.