I am pulling my hair out, trying to solve a simple problem. I know there is some math step here that I am missing and I feel like I am right on the edge of the solution but I just can't get there.
What I am trying to do is write an algorithm to fill an element with squares, and once the element is filled, resize the squares, create a new row and keep filling. Once both new rows are filled, append another row. Basically a line feed type algorithm?
So what I have so far works on the first row, but fails after that as it keeps resizing the unnecessarily.
$(function(){ //DOM Ready
//get columns of even squares
var columns = parseInt($(".grid").width()/$(".grid").height());
var rows = 1;
function checkSize(ico,index){
var grid,gridWidth,gridHeight
var icon,iconWidth,iconHeight
//get our grid info
grid = $(".grid");
gridWidth = grid.width();
gridHeight= grid.height();
//get our icon info
icon = $(ico);
iconWidth = icon.outerWidth();
iconHeight = icon.outerHeight();
//will go over columns?
if(index >= columns){
//do we need another row?
if(Math.floor(gridHeight/iconHeight) === rows){
//add row
rows++;
//reset columns
columns = gridWidth / Math.floor(gridHeight / rows);
//resize boxes
size();
};
}
};
function size(){
var grid,icon,newHeight;
grid = $(".grid");
newHeight = (grid.height()/rows)
$.each(grid.children(".icon"),function(index,value){
icon = $(value);
icon.css("height",newHeight+'px');
icon.css("width",newHeight+'px');
});
}
//fill
var counter = 0;
function fillGrid(){
var icon,grid,r,g,b,a
icon = $('<div class="icon"></div>');
//random color
r = Math.floor(Math.random()*256);
g = Math.floor(Math.random()*256);
b = Math.floor(Math.random()*256);
a = 1;
icon.css('background-color','rgba('+r+','+g+','+b+','+a+')')
grid = $(".grid");
grid.append(icon);
size(icon);
checkSize(icon,counter);
counter++;
};
var timeoutID;
function start(){
if(timeoutID){
clearInterval(timeoutID);
timeoutID = undefined;
}else{
timeoutID = window.setInterval(fillGrid, 1000);
}
};
//START THE TIMER
$('#start').on('click',start);
});
See the working example here-
http://jsbin.com/ovewib/7/edit
Any help would be greatly appreciated!