lisovaccaro lisovaccaro - 4 months ago 8
Javascript Question

Listen for browser width for responsive web design?

I'm trying to make my site mobile friendly.

I want to know the browser window size so that I do something when it's narrower than 728px and something else when it's bigger.

This must take into account resizing the window on the PC as well as changing from portrait to landscape mode in a phone.

How can this be done?

Answer

As m90 suggest, if the only thing you want to do is modify the style, then you should have a look at media queries. However, if you want to do more than just modify the style, then you have to rely on JavaScript.

Plain JavaScript

The problem is that it isn't entirely straight forward to get the width of the window, it varies between browsers. So you would have to create a function, something like this (untested):

var width = 0;
function updateWindowSize() {
    if (document.body && document.body.offsetWidth) {
      width = document.body.offsetWidth;
    }
    if (document.compatMode=='CSS1Compat' &&
        document.documentElement &&
        document.documentElement.offsetWidth ) {
       width = document.documentElement.offsetWidth;
    }
    if (window.innerWidth) {
       width = window.innerWidth;
    }
}

Then you could listen for for the window onresize event, and call the function to get the new window size everytime the window changes.

window.onresize = function(event) {
    updateWindowSize();
}

jQuery

If you use jQuery, then this can be done a bit shorter, as jQuery takes care of the cross-browser-support for you behind the scenes:

var width;
$(window).resize(function() {
  width = $(window).width();
});
Comments