Skip to main content
3 of 3
Fixed some issues that prevented the box from jumping forever.

var GRAVITY = 0.08;
var SPEED = 1; //1 is fastest
var dx = [];
var dy = [];
var maxX = window.innerWidth;
var maxY = window.innerHeight;
var all = [];// = document.getElementsByTagName("*:visible");
var positions = [];
var widths = [];
var heights = [];

function drop() {

    $("*").each(function(index) {
        all.push(this);
        positions.push($(this).offset());
        widths.push($(this).width());
        heights.push($(this).height());
    });
  
    for(var i=0; i < all.length; i++) {
        all[i].style.position = "fixed";
        all[i].style.top = positions[i].top+"px";
        all[i].style.left = positions[i].left+"px";
        dx[i] = Math.random() * 4 - 2;
        dy[i] = Math.random() * 1;
    } 
  
    setInterval(mainLoop, SPEED);
}

function mainLoop() {
    for(var i=0; i < all.length; i++) {
        dy[i] += GRAVITY/2;
        positions[i].top += dy[i];
        positions[i].left += dx[i];
        dy[i] += GRAVITY/2;
        if(positions[i].left < 0) dx[i] *= -1;
        if((positions[i].left + all[i].offsetWidth) > maxX) dx[i] *= -1;
        if(positions[i].top > (maxY - all[i].offsetHeight)) dy[i] = -Math.abs(dy[i]);
        
        all[i].style.left = positions[i].left+"px";
        all[i].style.top = positions[i].top+"px";
    }
}

drop();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<html>
  <body>
<div style="border-style: solid; border-width: 5px; border-color:red;">Test</div>
  </body>
</html>