jquery, add/remove class when window width changes

jquery

Solution

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

Problem

I've written out a very basic script to add/remove a class on load or when a window is resized. I was just wondering if there was a better way of doing this or if it is possible to reduce the lines of code. Basically I want to be able to alter the styles when the site is viewed on a smaller screen. I thought it would be best to add a new class to the html tag when it went under a certain width... Anyways here's my code. ``` <script type="text/javascript"> $(document).ready( function() { /* Check width on page load*/ if ( $(window).width() < 514) { $('html').addClass('mobile'); } else {} }); $(window).resize(function() { /*If browser resized, check width again */ if ($(window).width() < 514) { $('html').addClass('mobile'); } else {$('html').removeClass('mobile');} }); ``` Thanks Gillian

Original source