jQuery window width matching CSS media query

Published by Lennart Van Vaerenbergh on August 14, 2015

When you want to get the exact same breakpoints in jQuery as you have in your CSS media queries, the script below does it. Using the window width like $(window).width() has a small difference in pixels due to the scrollbar which is annoyingly taken into account. Many other variations didn't work either for me. This one covers it all:

In your js file:
function viewport() {
  var e = window, a = 'inner';
  if (!('innerWidth' in window)) {
    a = 'client';
    e = document.documentElement || document.body;
  }
  return { width : e[a + 'Width'], height : e[a + 'Height'] };
}

var windowWidth = viewport().width;

Comments

Submitted by Peter on Friday, February 05, 2016 - 14:10
Thanks Lennart. So with this piece of code on the top of my script I can use `windowWidth` in blocks of code further down, or do I call `viewport()`?
Submitted by Lennart on Wednesday, February 24, 2016 - 10:44
Hi Peter, you can use "viewport().width" in your code where you need it. The variable "windowWidth" is just an example of how to call the function.

Add new comment

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.
CAPTCHA
This challenge is for testing whether or not you are a human visitor and to prevent automated spam submissions.