Search code examples
jqueryrefactoringreadabilitycode-readability

Can this jQuery code be refactored


I am trying to improve my jQuery skill and I have this bit of code. It's basic purpose is to size and resize a background to keep it at the same height as a responsive slider, so matching the size of the window; and tracking that if it's resized by the user.

Could it be refactored better or is it good as it is.

$(window).load(function() {
var height = $('#display-area').css('height');
$('.skin-background')
    .css('display', 'block')
    .css('height', height);
});
$(window).resize(function() {
var height = $('#display-area').css('height');
$('.skin-background')
    .css('height', height);
});

Solution

  • // Cache elements that get used more than once
    var $background = $('.skin-background');
    var $displayArea = $('#display-area');
    
    // Don't repeat yourself, put recurring actions in functions
    var resizeBackground = function() {
        $background.css({
            'display': 'block',
            'height': $displayArea.height() + 'px'
        });
    };
    
    $(window).load(resizeBackground).resize(resizeBackground);
    

    You should also consider to "throttle" the event handler for the resize event, because some browsers fire a lot of them when resizing the window. Using underscore.js, this would then be:

    $(window).load(resizeBackground).resize( _.throttle(resizeBackground, 100) );