Div Bouncer

by vicky081

HTML

<div id="container">
    <img class="contain" src="http://placekitten.com/g/100/100">
    <div class="message contain">Hi, I'm a bouncing div!</div>
    <img  class="contain"  src="http://placekitten.com/g/100/102">
</div>

CSS

#container {
    position: absolute;
    width: 100%;
    height: 100%;
  

 
    border: 2px solid black;
    background: lightBlue;
}
.contain {
cursor: pointer;
	cursor: hand; 
}


#container img {
    position: absolute;
    border: 3px solid #6D98A6;
}

.message {
    position: absolute;
    width: 110px;
    height: 40px;
    padding: 10px;
    background-color: lightGreen;
    border: 3px solid yellow;
    text-align: center;    
}

JavaScript

$(function() {

    var minSpeed = .02;
    var maxSpeed = .06;
    var varSpeed = .005;

    function startBounce(elements) {
        elements.each(function(i, element) {
            var el = $(element);
            var container = el.parent();
            var width = container.innerWidth() - el.outerWidth();
            var height = container.innerHeight() - el.outerHeight();

            var vertSpeed = ((Math.random() * (maxSpeed - minSpeed)) + minSpeed);
            var horzSpeed = ((Math.random() * (maxSpeed - minSpeed)) + minSpeed);
            bounce(el, vertSpeed, height, 'top');
            bounce(el, horzSpeed, width, 'left');
        });
    }

    function bounce(img, speed, max, dir) {
        speed += ((Math.random() * varSpeed) - (varSpeed / 2));
        speed = speed < minSpeed ? minSpeed : (speed > maxSpeed ? maxSpeed : speed)
        var time = max / speed;
        var position = img.position();
        var target = (position[dir] < 2) ? max : 0;

        var style = {
            queue: false
        };
        style[dir] = target;
        img.animate(style, {
            duration: time,
            queue: false,
            easing: "linear",
            complete: function() {
                bounce(img, time, max, dir);
            }
        });
    }

    startBounce($('#container *'));

    $('#stop').click(function() {
        $('*').stop(true);
    });
});