Using jQuery to detect window size to add a class

Have you ever needed to add a class to the body tag dynamically depending on the browser window resolution?  Generally to do this in the easiest sense requires browser sniffing, something that really isn’t a good idea.  It’s one of the slower functions that you could call on to use in JavaScript.

Most people who know a bit of jQuery would probably try this route;

function checkWindowSize() {  
    if ( $(window).width() > 1024) { 
        $('body').addClass('w1280');  
        } else {  
        $('body').removeClass('w1280');  
    } 
    if ( $(window).width() > 1280 ) { 
        $('body').addClass('w1440');  
        } else {  
        $('body').removeClass('w1440');  
    } 
    if ( $(window).width() > 1440) { 
        $('body').addClass('w1680');  
        } else {  
        $('body').removeClass('w1680');  
    } 
    if ( $(window).width() > 1600) { 
        $('body').addClass('wLarge');  
        } else {  
        $('body').removeClass('wLarge');  
    } 
}    
checkWindowSize();

That is wrong is too many ways – and doesn’t really work in the real world as a good solution. But if you REALLY need to do that then maybe the following may help;

function checkWindowSize() {
    var width = $(window).width(),
    new_class = width > 1600 ? 'wLarge' :
                width > 1440 ? 'w1680' :
                width > 1280 ? 'w1440' :
                width > 1024 ? 'w1280' : '';

    $(document.body).removeClass('wLarge w1680 w1440 w1280').addClass(new_class);
}
checkWindowSize();

Again, I simply don’t recommend this method, but if the situation was unavoidable then you would have to pick your poison. Boilerplate offer a complete solution, but you’ll have to reverse engineer the framework to get it to work properly in a none HTML5 environment (such as html 4.01 transitional/strict DOCTYPE).

4 Comments

  1. Ric says:

    I read your post and wished I was good enough to write it

  2. car insurance quote says:

    Hello, I log on to your blog on a regular basis. Your writing style
    is witty, keep up the good work!

  3. source says:

    Wanted to drop a comment and let you know your Feed is not functioning today. I tried including it to my Bing reader account and got absolutely nothing.

Leave a Reply

Your email address will not be published. Required fields are marked *