Detect browser/screen width

In addition to media queries with CSS I want JavaScript to also perform some actions based on screen/browser width.

As an example, when the browser is extended greater than 1400px as well as media queries showing more options in the top navigation bar, I would like JavaScript to perform an Ajax request to get additional data. This is just an example, but I want to do various things like this.

I only need to know a cross-browser and reliable way to detect the browser width so JS returns exactly the same value as media queries does?

This should detect it correctly on desktops, laptop, tablets and mobiles.

I believe in jQuery you can perform $(window).width()

And you can attach an event to resize(), so it runs when the user resizes their browser window


$(function()
{
  $(window).bind('resize', function()
    {
       // grab the width
       var width = $(this).width();
    }
  );
});

Granted, you will need to run this function on DOM load too, as the resize event is only called when the window size changes.

Just remembered, you might also have success with document.documentElement.clientWidth and/or document.body.clientWidth

Different browsers track the viewport width in different fields. The following is the shortest code that will get the value from whichever of the three places that the browser uses.

var viewportWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;