SO - 20942541
HTML
<div id="container">
<img class="cat" src="http://placekitten.com/250/250" />
</div>
CSS
div#container {
position: absolute;
top: 50%;
left: 50%;
width: 250px;
height: 250px;
margin-left: -125px;
/* Half the width */
margin-top: -125px;
/* Half the height */
}
img.cat {
position: absolute;
top: 50%;
left: 50%;
width: 250px;
height: 250px;
margin-left: -125px;
/* Half the width */
margin-top: -125px;
/* Half the height */
cursor: pointer;
}
JavaScript
var explode;
$('img.cat').click(explode = function () {
var contW = $(document).width();
var contH = $(document).height();
//alert(contW);
//alert(contH);
for (var i = 1; i <= 3; i++) {
var source = $(this).position();
var posNeg = Math.random() < 0.5 ? -1 : 1;
var newTop = Math.floor(Math.random() * (contH / 2 + (posNeg * $(this).height()))) * posNeg;
var posNeg = Math.random() < 0.5 ? -1 : 1;
var newLeft = Math.floor(Math.random() * (contW / 2 + (posNeg * $(this).width()))) * posNeg;
var $kitty = $(this).clone().css({
width: $(this).width() / 2,
height: $(this).height() / 2
});
$('#container').append($kitty);
// constrain newTop and newLeft
if (newTop < 0){
newTop = 0;
}
if (newTop > contH){
newTop = contH;
}
if (newLeft < 0){
newLeft = 0;
}
if (newLeft > contW){
newLeft = contW;
}
$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)
});