Skip to content
Advertisement

CSS media queries and jQuery window .width() do not match

For a responsive template, I have a media query in my CSS:

JavaScript

And, I made a jQuery function on resize to log the width:

JavaScript

And there a difference with CSS detection and JS result, I have this meta:

JavaScript

I suppose it’s due to the scrollbar (15 px). How can I do this better?

Advertisement

Answer

You’re correct about the scroll bar, it’s because the CSS is using the device width, but the JS is using the document width.

What you need to do is measure the viewport width in your JS code instead of using the jQuery width function.

This code is from http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement