Pergunta

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);
});
Foi útil?

Solução

// 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) );

Outras dicas

You can use single selector for adding both events and can set multiple css attributes like this

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

}).resize(function() {
var height = $('#display-area').css('height');
$('.skin-background')
    .css('height', height);
}); 
$(window).on("load resize",function() {
var height = $('#display-area').height();
$('.skin-background')
    .css({'display':'block','height':height});
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top