JSFiddle - React, Tailwind, and code Playground
by Johan Muller
JavaScript
$(document).ready(function(){
var masterBox = function(){
var $boxParent = $('.box-parent');
var $box = $boxParent.find('.box');
var i; // universal index
var canvasWidth = $boxParent.width();
var cellWidth = 100;
var cellHeight = 100;
var matrixGradeX = parseInt(canvasWidth/cellWidth);
var matrixGradeY = 10; // max height cells
var matrixArray = new Array(matrixGradeX);
for (i=0;i<matrixGradeX;i++) { matrixArray[i]=new Array(matrixGradeY); }
$box.each(function(boxIndex,boxElement){
var $b = $(boxElement);
var style,debug;
var thisBoxMatch = $b.attr('class').match(/size(\d+)x(\d+)/);
var thisBoxSize = [thisBoxMatch[1],thisBoxMatch[2]];
var cx,cy;
var hasResult = false;
for (cy=0;cy<matrixGradeY;cy++) {
for (cx=0;cx<matrixGradeX;cx++) {
var cellFree = !matrixArray[cx][cy];
if (cellFree) {
hasResult = true;
matrixArray[cx][cy] = true;
}
if (hasResult) { break; }
}
if (hasResult) { break; }
}
debug = cx+'x'+cy;
style = 'top:'+(cy*cellHeight)+'px;left:'+(cx*cellWidth)+'px;';
$b.attr('style',style);
$b.attr('data-debug',debug);
});
var matrixDebug = '';
for (cy=0;cy<matrixGradeY;cy++) {
for (cx=0;cx<matrixGradeX;cx++) {
var cellFree = !matrixArray[cx][cy];
if (cellFree) { matrixDebug+='0'; } else { matrixDebug+='1'; }
}
console.log(matrixDebug);
matrixDebug = '';
}
};
var $mbTarget = $(window), mbEvent = 'resize';
$mbTarget.on(mbEvent,masterBox).trigger(mbEvent);
});