<!-- Begin snippet: js -->

<!-- language: lang-js -->

    var B0=null,B1=null,MAXV=3.0,TWOPI=2.0*Math.PI;

    function Ball(b)
    {
     this.b=b;
     this.vy=3.0 + MAXV*Math.sqrt(Math.random());
     var temp=Math.random()*TWOPI; 
     this.vx=this.vy*Math.cos(temp);
     this.vy*=Math.sin(temp); 
     this.x=this.y=null;
      
     return this;
    }

    function moveBalls()
    {
     var temp=B0.x + B0.vx;
     if ( 10<temp && temp<140 ) B0.x=temp; else B0.vx=(-B0.vx);
     temp=B0.y + B0.vy;
     if ( 10<temp && temp<140 ) B0.y=temp; else B0.vy=(-B0.vy);
     temp=B1.x + B1.vx;
     if ( 10<temp && temp<140 ) B1.x=temp; else B1.vx=(-B1.vx);
     temp=B1.y + B1.vy;
     if ( 10<temp && temp<140 ) B1.y=temp; else B1.vy=(-B1.vy);
     if ( Math.sqrt(Math.pow(B0.x - B1.x,2) + Math.pow(B0.y - B1.y,2))<=20 ) {
        (temp=B0.vx),(B0.vx=B1.vx),(B1.vx=temp);
        (temp=B0.vy),(B0.vy=B1.vy),(B1.vy=temp);
      }
     B0.b.style.left=Math.round(B0.x) - 10 + "px";
     B0.b.style.top=Math.round(B0.y) - 10 + "px"; 
     B1.b.style.left=Math.round(B1.x) - 10 + "px";
     B1.b.style.top=Math.round(B1.y) -10 + "px";  
     setTimeout(moveBalls,46);
    }


    window.onload
    =function ()
    {
     B0=document.getElementsByTagName("p"); 
     B1=new Ball(B0[0]);
     B0=new Ball(B0[1]); 
     B0.b.style.backgroundColor="#f00";
     B0.x=25; 
     B0.b.style.left=B0.x + "px";
     B0.y=75; 
     B0.b.style.top=B0.y + "px"; 
     B1.b.style.backgroundColor="#00f";
     B1.x=110; 
     B1.b.style.left=B1.x + "px";
     B1.y=75; 
     B1.b.style.top=B1.y + "px"; 
     moveBalls();
    };

<!-- language: lang-css -->

    div, p
    {
      border:0;
      margin:0;
     padding:0; 
    }

    div
    {
              position:relative;
                 width:150px;
                height:150px;
                margin:0 auto;
                border:1px solid #000;
      background-color:#ffe;
    }

    div p
    {
          position:absolute;
             width:20px;
            height:20px;
     border-radius:10px;
    }

<!-- language: lang-html -->

    <div><p></p><p></p></div>

<!-- end snippet -->