Exploding children
by Adam Granger
HTML
<div class="parent">
</div>
<button>3</button>
<button>5</button>
<button>8</button>
CSS
.parent {
width: 300px;
height: 300px;
border: 1px solid red
}
.child {
width: 20px;
height: 20px;
overflow:hidden;
border: 1px solid green;
position: absolute;
}
JavaScript
function redraw(parent, radius, spin) {
var centerX = parent.width() / 2;
var centerY = parent.height() / 2;
var count = parent.find(".child").length;
parent.find(".child").each(function(i, child) {
var child =$(child);
var x = centerX + radius * Math.sin(spin / 50 + i / count * 2 * Math.PI);
var y = centerY - radius * Math.cos(spin / 50 + i / count * 2 * Math.PI);
child.css("left", x - child.width() / 2);
child.css("top", y - child.height() / 2);
});
}
$("button").click(function() {
var count = $(this).text();
var children = [];
$(".parent").empty();
for (var i = 0; i < count; i++) {
var child = $('<div class="child"></div>');
child.text(i);
children.push(child)
$(".parent").append(child);
}
this.radius = 0;
this.animate = function() {
console.log(this.radius);
redraw($(".parent"), this.radius, this.radius);
this.radius++;
if (this.radius > 100) {
window.clearInterval(this.timer);
};
};
this.timer = window.setInterval(this.animate.bind(this), 20);
});