lisovaccaro
lisovaccaro

Reputation: 33956

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?

Upvotes: 4

Views: 12724

Answers (2)

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

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();
});

Upvotes: 9

LisKit
LisKit

Reputation: 11

As a warning, IE8 and lower don't support media queries or CSS3. If you don't care about IE8, go for it. Respond.js, Modernizr and others can help to support IE6-8, but it's far from perfect.

Upvotes: 1

Related Questions