I did it with JQuery.
Here is the math behind - without trigonometric functions.
Make a small step with one Ball to the direction you want it to go.
function pushball(distance,x,y,xgoal,ygoal,step){/
var factor=1-step/distance;
var x=xgoal+(xgoal-x)*factor;
var y=ygoal+(ygoal-y)*factor;
return [x,y];
Check all other balls[i] whether they collide.
function distance(x1,y1,x2,y2){
var x=x1-x2;var y=y1-y2;
return Math.sqrt(x*x+y*y);
}
var dist=distance(x,y,x[i],y[i]);
var touch=r+r[i];
Now - on a straight line through the two center point - push the other balls (if they collide) so that they just touch each other.
if(dist<touch){
var range=dist-touch;
newposxy=pushball(distance,x,y,x[i],y[i],range);
}
Slide each ball[i] whose position has changed. Aware that x,y are the coordinates of the middle point and not of the top left corner.
$("#ball").offset({"left":Math.round(x[i]-r),"top":Math.round(y[i]-r)});
If you want to see it working see here