jquery, add/remove class when window width changes

Well, I know I’m late to the party, but I saw some things like $(document).ready() that weren’t really necessary.

Try to cache your selectors if you’re calling them over and over again, a la var $window = $(window); This will help with performance. I use a function expression to encapsulate to I stay out of the global scope but still have access to my $window and $html cached jQuery selected elements.

(function($) {
    var $window = $(window),
        $html = $('html');

    $window.resize(function resize(){
        if ($window.width() < 514) {
            return $html.addClass('mobile');
        }

        $html.removeClass('mobile');
    }).trigger('resize');
})(jQuery);

http://jsfiddle.net/userdude/rzdGJ/1

Probably a little cleaner, little easier to follow:

(function($) {
    var $window = $(window),
        $html = $('html');

    function resize() {
        if ($window.width() < 514) {
            return $html.addClass('mobile');
        }

        $html.removeClass('mobile');
    }

    $window
        .resize(resize)
        .trigger('resize');
})(jQuery);

http://jsfiddle.net/userdude/rzdGJ/2

Leave a Comment