SO - 20942541

by abhitalks

HTML

<div id="container">
    <img class="cat" src="http://placekitten.com/250/250" />
</div>

CSS

html, body { width:100%; height: 100%; }
div#container {
    position: relative;
    width: 350px;
    height: 350px;
    border: 1px solid gray;
}
img.cat {
    position: absolute;
    top: 10%;
    left: 10%;
    width: 250px;
    height: 250px;
    cursor: pointer;
}

JavaScript

var explode;
var contW = $('#container').width();
var contH = $('#container').height();

$('img.cat').click(explode = function () {

    for (var i = 1; i <= 3; i++) {
        var source = $(this).position();
        var posNeg = Math.random() < 0.5 ? -1 : 1;
        var newTop = getRandomInt(1, contH);
        //var newTop = Math.floor(Math.random() * (contH / 2 + (posNeg * $(this).height()))) * posNeg;
        var posNeg = Math.random() < 0.5 ? -1 : 1;
        var newLeft = getRandomInt(1, contW);
        //var newLeft = Math.floor(Math.random() * (contW / 2 + (posNeg * $(this).width()))) * posNeg;
console.log(newTop + ", " + newLeft);
        var $kitty = $(this).clone().css({
            width: $(this).width() / 2,
            height: $(this).height() / 2
        });
        $('#container').append($kitty);
        $kitty.css({
            top: source.top,
            left: source.left
        })
            .animate({
            top: newTop + 'px',
            left: newLeft + 'px'
        }, 300)
            .click(explode);
    }

    var $this = $(this);
    var $lion = $('<img class="cat" src="http://images1.wikia.nocookie.net/__cb20130326142633/warriors/images/4/47/Lion.png" />').css({
        left: $this.css('left'),
        top: $this.css('top'),
        width: $this.width(),
        height: $this.height()
    });
    $this.replaceWith($lion)
    setTimeout(function () {
        $lion.remove()
    }, 1000)
});

function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}