Bouncing Ball - animation js

by Alan November

HTML

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

CSS

#ball {position:absolute;border-radius:50%;width:20px;height:20px;background-color:red;}
#ground {border:2px solid brown;position:relative;top:313px;}

JavaScript

var ball={x:0,y:0,xs:10,ys:0};// initial speed

function ticker(){
    //debugger;
    ball.xs*=0.5;// friction
    ball.x+=ball.xs;
    ball.ys+=0.2; // gravity
    ball.ys*=0.9; // friction
    ball.y+=ball.ys;
    if (ball.y > 300 && ball.ys>0){ // hit the deck
        ball.ys = -ball.ys*0.9; // loose energy in bounce
    }
    $('#ball').css({'left':ball.x+'px','top':ball.y+'px'});
    if(Math.abs(ball.xs)>0.001 && Math.abs(ball.ys)>0.001){ // stop when x/y speeds are very slow.
        setTimeout(ticker,10);
    }else{
        console.log('stop')
    }
}


ticker()