views:

881

answers:

3

Hi everyone, I am trying to punch above my weight with jQuery, and have run into a problem which has me stumped.

Basically, I am trying to get a truck to animate from the left hand side of the screen to the right, then when it gets to the right of the screen, the background image of the truck swaps to an image of the truck facing the other way, and it then animates back across the screen, and will repeat for ever.

I can get the truck to move across the screen, and swap the background image, but cannot get everything to happen in some sort of logical order - I.E. the truck background image is swapped on page-load and not when the left to right has completed.

Here is the code so far, and I realize that the syntax is probably wrong, but hopefully you will see what I am trying to do:

$(document).ready(function() {

    $(".animationWrap").animate({ left: "845px" }, { duration: 9000, queue: true }){
 $(".animationWrap").css('background', 'transparent url(/Resources/Images/clearence/truckLeft.png) no-repeat 0 0');
}

});
+1  A: 

use a callback function on the first .animate, which fires after it is complete, to do things in order (see the syntax for jQuery Animate):

$(document).ready(function() {

    $(".animationWrap").animate({ left: "845px" }, 9000, function() {
        css('background', 'transparent url(/Resources/Images/clearence/truckLeft.png) no-repeat 0 0');
        animate({ left: 0 }, 9000);
    });
});
carillonator
Thanks for your help. I am 90% there now and understand callbacks more than I did an hour ago!
Luke
+1  A: 

You need to use the callback - which will get fired when the animation is complete. Sometimes it helps to create this as a named function so you can reuse it.

$(document).ready(function() {
     $('.animationWrap');.animate({ left: "845px" }, { duration: 9000, queue: true }, animationComplete ); 
});

function animationComplete(){
    $(this).css('background', 'transparent url(/Resources/Images/clearence/truckLeft.png) no-repeat 0 0');
}
redsquare
Thanks for your help. I am 90% there now and understand callbacks more than I did an hour ago!
Luke
A: 

This is what I did to get it working. I also used a plugin called jQuery timers to get the animation to repeat indefinately. Thanks for your help everyone.

$(document).ready(function() {
        $(".animationWrap").everyTime(0, function() {

            $(".animationWrap").animate({ left: "845px" }, 35000, function() {
            $(this).css('background', 'transparent url(/Resources/Images/clearence/truckLeft.png) no-repeat 0 0');
        });
        $(".animationWrap").animate({ left: "-1px" }, 35000, function() {
            $(this).css('background', 'transparent url(/Resources/Images/clearence/truckRight.png) no-repeat 0 0');
        });       

    });

});

Luke