jquery detect window resize

Jgammel picture Jgammel · Feb 25, 2013 · Viewed 17.6k times · Source

I have a question about a site I'm working on regarding detecting when the window is resized. I know this has been discussed previously and I've read through many of the discussions and just couldn't get it to work. I'm just learning jquery.

 $(function(){
    var viewPortWidth = $(window).width();
    if (viewPortWidth > 1900)
    {
       $('#mainbio, #footerlinks').addClass('extraWide')
    }
    else if (viewPortWidth > 1400)
    {
       $('#mainbio, #footerlinks').addClass('wide')
    }
    else if (viewPortWidth > 1000) 
    {
       $('#mainbio, #footerlinks').addClass('standard')
    }
    else if (viewPortWidth > 700)
    {
       $('#mainbio, #footerlinks, #twitter, #facebook, #flickr,   #lastfm').addClass('narrow')
    }
    else 
    {
       $('#mainbio, #footerlinks, #twitter, #facebook, #flickr, #lastfm').addClass('extraNarrow')
    }
 });

This is what I have so far and it works fine, but only on the initial load. I'm wondering if someone can help me adjust this so it will work dynamically - so I could see the changes if I were to manually resize my browser, without refreshing?

Thanks!

Answer

dev picture dev · Feb 25, 2013

You can call back this function using .resize().

e.g.

var detectViewPort = function(){
    var viewPortWidth = $(window).width();
    if (viewPortWidth > 1900)
    //...The rest of your above code.
};

$(function(){
  detectViewPort();
});

$(window).resize(function () {
   detectViewPort();
});

There maybe another/better way around this but this is the option I know about.