Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 252
lisovaccaro Avatar asked Dec 28 '22 01:12

lisovaccaro


2 Answers

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();
});
like image 161
Christofer Eliasson Avatar answered Jan 13 '23 21:01

Christofer Eliasson


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.

like image 43
LisKit Avatar answered Jan 13 '23 20:01

LisKit