Question

I'm trying to animate a ball that bounces and moves forward. First the ball must bounce X times in the same place but then it must go forward bouncing.

BOUNCE:

$("#ball").animate({top:"-=5px"},150).animate({top:"+=5px"},150);

MOVING:

$("#ball").animate({"left":"850px"},2800);

Any suggestion?

Was it helpful?

Solution 2

Here's one approach. To get the ball to bounce X times, we can create a recursive function which takes advantage of jQuery animation queues:

function bounce(n) {
    if (n > 0) {
        $("#ball").animate({top: "-=5px"}, 150)
            .animate({top: "+=5px"}, 150, function() {
                bounce(n-1); 
            });
    }
};
bounce(3);

To get it to roll afterwards and continue bouncing, we need to use .dequeue() to run both animations at once:

$("#ball").animate({"left": "850px"}, 2800).dequeue();
bounce(10);

Now, to combine them, create a special callback function which will only run after the Xth bounce:

function bounce(n, callback) {
    if (n > 0) {
        $("#ball").animate({top: "-=5px"}, 150)
            .animate({top: "+=5px"}, 150, function () {
                bounce(n-1, callback);
            });
    } else if (callback) { // might be undefined
        callback();
    }
};

bounce(3, function() {
    $("#ball").animate({"left": "850px"}, 2800).dequeue();
    bounce(10);
});

http://jsfiddle.net/mblase75/c72Qj/

OTHER TIPS

here's a fiddle that does what you want, you can tweak it fairly easily:
http://jsfiddle.net/2LyWM/

$(document).ready(function(){

    $("#ball").queue( function() {

        $(this).animate({top:'+=50px'}, { duration: 500, queue: true });
        $(this).animate({top:'0px'}, { duration: 500, queue: true });
        $(this).animate({top:'+=50px'}, { duration: 500, queue: true });
        $(this).animate({top:'0px'}, { duration: 500, queue: true });
        $(this).animate({top:'+=50px'}, { duration: 500, queue: true });
        $(this).animate({top:'0px'}, { duration: 500, queue: true });
        $(this).animate({top:'+=50px'}, { duration: 500, queue: true });        
        $(this).animate( {left:'+=100px'}, { duration: 2500, queue: false });

        $.dequeue( this );
    });

});

html

<div id="ball">ball</div>

css

#ball{
    top: 0px;
    left: 0px;
    position: relative;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top