JSFiddle - React, Tailwind, and code Playground
by hephistocles
HTML
<div id="initialDiv" class="divider"><div class="inner"></div></div>
CSS
#initialDiv{
height:500px;
width:500px;
}
.divider {
position:absolute;
}
.inner {
height:100%;
width:100%;
background-color:#123;
}
JavaScript
$("#initialDiv").bind('click', divide);
function divide(e) {
// backup the original div without modifications
var origDiv = $(this).clone();
var parent = $(this);
// remove the click handler so that we don't try to divide the same div twice
parent.unbind('click');
// loop through and create four new divs by cloning the original
for (var i = 0; i < 4; i++) {
var newDiv = origDiv.clone();
// initially set the dimensions to 0 so it can increase in size through animation
newDiv.css({
"height": 0,
"width": 0
});
//animate the size increase (size = 0.49 to make a small gap)
newDiv.animate({
"height": $(this).height() * 0.49,
"width": $(this).width() * 0.49
}, function() {
// after the animation
// you may like to remove the original div
parent.children(".inner").remove();
});
/**
* because of the animation, standard HTML flow won't maintain
* the right position, so we need to set absolute positions
*/
if (i % 2 == 0) {
newDiv.css({
"left": "51%",
"right": "auto"
}); // 51% for the gap
} else {
newDiv.css({
"right": "51%",
"left": "auto"
});
}
if ((i - i % 2) / 2 == 0) {
newDiv.css({
"top": "51%",
"bottom": "auto"
});
} else {
newDiv.css({
"bottom": "51%",
"top": "auto"
});
}
// attach a click handler for further subdivision
newDiv.bind('click', divide);
// assign a random colour to the new div
var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
...