Logo  

CS479/579 - Web Programming II

Displaying ./code/ES/boxes.html

<!DOCTYPE html>
<html>
<head>
 <title> Boxes game </title>
 <meta charset='utf-8'>
 <style>
 .box {
   width: 100px; height: 100px; border: 1px solid black;
   position: absolute;
   border-radius: 50px;
 }
 body {
   overflow: hidden;
 }
 </style>
 <script>
 var _boxes = [];

 function R(min, max)
 {
   var range = Math.abs(max-min);
   return Math.floor((Math.random()*range)) + min;
 }

 function update()
 {
   for(var box of _boxes) {
     box.x += box.dx;
     box.y += box.dy;
     if (box.x < 0 || box.x > window.innerWidth-100) box.dx = -box.dx;
     if (box.y < 0 || box.y > window.innerHeight-100) box.dy = -box.dy;
     box.box.style.top = box.y + "px";
     box.box.style.left = box.x + "px";
   }
   setTimeout(update, 16);
 }

 function pop(e, ev)
 {
   console.log(e);
   for(var i in _boxes) {
     if (e == _boxes[i].box) {
       document.body.removeChild(e);
       _boxes.splice(i, 1);
     }
   }
 }

 function gen()
 {
   for(var i = 0; i < 100; i++) {
     var box = document.createElement("div");
     box.setAttribute("class", "box");
     var x = R(0,window.innerWidth-100);
     var y = R(0,window.innerHeight-100);
     var dx = R(-5,5);
     var dy = R(-5,5);
     box.style.top = y + "px";
     box.style.left = x + "px";
     box.innerHTML = "&nbsp;";
     _boxes.push({box: box, x: x, y: y, dx: dx, dy: dy});
     box.setAttribute("onmouseenter","pop(this,event);");
     document.body.appendChild(box);
   }
   setTimeout(update, 16);
 }
 </script>
</head>
<body onload='gen();'>
</body>
</html>