Sam
Sam

Reputation: 97

Animating a box to meet at a calculated width

I'll be honest, I've patched together code from a couple of sources without really knowing how it works and I've confused the hell out of myself.

I have a series of images in a div (.projectImages) and I want to calculate the combined width of them then pass that value on to the animation so that it moves the images along by ther combined width.

Here's my frankenstein code:

function calcWidth() {
    var imgwidth = 0;
    $(".projectImages").find("img").each(function(){
        imgwidth += $(this).width();
    });
    return imgwidth;
}


$(function(){   
    $("#rightArrow").hover(function() {
        $('.projectImages').animate({left: imgwidth +'px'}, 3000);
    },function() {
        $('.projectImages').stop();
    });
});

I'm fairly sure the problem is in calculating the widths but as I said this code is a copy and paste job so I'm not really sure how it's working.

Fairly new to jQuery but I'm getting there slowly.

Upvotes: 0

Views: 167

Answers (2)

Florin P.
Florin P.

Reputation: 1

$('.projectImages').animate({left: calcWidth() +'px'}, 3000);

watch out if images have margin/padding, should be included as well in calculation

Upvotes: 0

jAndy
jAndy

Reputation: 235982

It looks not really wrong (logically). The syntax is a little off, you're using imgWidth within the $() (document ready) method. But it should throw a reference error.

You should replace imgWidth with calcWidth() and be fine.

Upvotes: 1

Related Questions