Div Bouncer

by Chandana Thota

HTML

<div id="container">
    <img src="http://placekitten.com/g/100/100">
</div>

<button id="stop">Stop!</button>

CSS

#container {
    position: absolute;
    width: 300px;
    height: 200px;
    margin-left: -150px;
    margin-top: -100px;
    top: 50%;
    left: 50%;    
    border: 2px solid black;
    background: lightBlue;
}

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

JavaScript

$(function() {

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

    function startBounce(img) {
        var container = img.parent();
        var width = container.innerWidth() - img.outerWidth();
        var height = container.innerHeight() - img.outerHeight();

        var vertSpeed = ((Math.random() * (maxSpeed - minSpeed)) + minSpeed);
        var horzSpeed = ((Math.random() * (maxSpeed - minSpeed)) + minSpeed);
        bounce(img, vertSpeed, height, 'top');
        bounce(img, 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();
        if (position[dir] < 2) {
            target = max;
        } else {
            target = 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 img'));

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