sambadave
sambadave

Reputation: 23

each() function. Can someone advise me how to shorten this code

The code I have below works fine but I'm sure it could be more streamlined.

The script basically resizes an image and positions it horizontally in the centre of its containing div no matter the screen size.

The two functions within function "resizeBg" are identical apart from the fact that they point at different divs (".block1" and ".block2") containing an image with a different class (".bg1" and ".bg2").

I need the function resizeBG to be applied separately to each div. One image could be portrait while the other could be landscape so the outcome is different depending on the image proportions. This is the only way I can get this to work just now but I realise it could be so much simpler/neater.

HTML

<div class="block block1">
    IMAGE
</div>
<div class="block block2">
    IMAGE
</div>

CSS

.block1 {background: #000000;}
.block2 {background: ffffff;}

.block {
    float: left;
    width: 50%;
    height: 100%;
    overflow: hidden;
    }

.bgwidth { 
  width: 100%;
  }

.bgheight { 
  height: 100%;
  }

jQuery

jQuery(window).load(function() {
// FULLSCREEN BACKGROUND IMAGE
var theWindow = $(window);
var block1 = $('.block1');
bg1 = block1.children(".bg1");
var block2 = $('.block2');
bg2 = block2.children(".bg2");
aspectRatio1 = bg1.width() / bg1.height();
aspectRatio2 = bg2.width() / bg2.height();

function resizeBg() {

    $('.block1').each(function() {
        if ((block1.width() / block1.height()) < aspectRatio1) {
            bg1.removeClass('bgwidth').addClass('bgheight');
            if(bg1.width() > block1.width()) {
                bg1.each(function(){
                    //get width (unitless) and divide by 2
                    var hWide = ($(this).width() - block1.width())/2;
                    // attach negative and pixel for CSS rule
                    hWide = '-' + hWide + 'px';
                    $(this).addClass("js-fix").css({
                        "margin-left" : hWide
                        });
                    });
                }
            else {
                bg1.each(function(){
                    $(this).removeClass("js-fix").css({
                        "margin-left" : 0 + 'px'
                        });
                    });
                };
        } else {
            bg1.removeClass('bgheight').addClass('bgwidth');

            bg1.each(function(){
                $(this).removeClass("js-fix").css({
                    "margin-left" : 0 + 'px'
                });
            });
        }

    });




    $('.block2').each(function() {
        if ((block2.width() / block2.height()) < aspectRatio2) {
            bg2.removeClass('bgwidth').addClass('bgheight');
            if(bg2.width() > block2.width()) {
                bg2.each(function(){
                    //get width (unitless) and divide by 2
                    var hWide = ($(this).width() - block2.width())/2;
                    // attach negative and pixel for CSS rule
                    hWide = '-' + hWide + 'px';
                    $(this).addClass("js-fix").css({
                        "margin-left" : hWide
                        });
                    });
                }
            else {
                bg2.each(function(){
                    $(this).removeClass("js-fix").css({
                        "margin-left" : 0 + 'px'
                        });
                    });
                };
        } else {
            bg2.removeClass('bgheight').addClass('bgwidth');

            bg2.each(function(){
                $(this).removeClass("js-fix").css({
                    "margin-left" : 0 + 'px'
                });
            });
        }

    });


}

theWindow.resize(function () {
    resizeBg();
}).trigger("resize");

});

Upvotes: 1

Views: 116

Answers (2)

King Friday
King Friday

Reputation: 26086

$('.block').each(function() {
    var $block = $(this), 
    blockWidth = $block.width(),
    blockHeight = $block.height(),
    blockRatio = blockWidth / blockHeight,
    className = $block.attr('class'),
    $bg = $('.bg' + className.substr(className.length-1)),
    bgWidth = $bg.width(),
    bgHeight = $bg.height(),
    bgRatio = bgWidth / bgHeight;

    if (blockRatio < bgRatio) {
        $bg.removeClass('bgwidth').addClass('bgheight');
        if(bgWidth > blockWidth) {
            $bg.addClass('js-fix')
            .css('margin-left',
            '-' + ((bgWidth - blockWidth)/2) + 'px';
        } else {
            $bg.removeClass('js-fix').css('margin-left','0');
        }
    } else {
        $bg.removeClass('bgheight').addClass('bgwidth')
        .removeClass('js-fix').css('margin-left','0');
    }
});

FYI: 0px === 0pt === 0em === 0

Upvotes: 0

Jason
Jason

Reputation: 52537

So I gave it a shot. Basically you just need to refactor your code so that it is more generic and can work on each element in your jQuery object. I'm not sure if this is exactly what you want, I didn't really pay attention too much to what was going on in the code, I just genericized it so that you don't have to write the same code twice. It may be able to be refactored further, this is just to give you an idea as to what you should be doing.

Upvotes: 1

Related Questions