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).

About Desi Reuben-Sealey


Desi is a Web Standards Interaction Warrior for the Web and Mobile, an enthusiastic PADI diver, retired pro UK basketball player, Neo Soul music lover, an enthusiastic charity worker who likes to give to others is various ways. Desi is also a mentor / business coach and co-owner of Return to Youth.

Short URL: http://bit.ly/LaGfMz
QR Code: