looking at related questions from the outside, I found an answer (more or less) written in another language. Trick should first calculate the number of rows and columns your grid should have (depending on the length of your array), then run a loop inside the loop, where the first loop repeats your rows and second columns.
here is javascript translation of this other answer
function popUp(){ // calculate number of rows and columns var cols = Math.ceil(Math.sqrt(queue.length)); var rows = Math.ceil(queue.length/cols); // calculate width and height based on number of cols && rows var W = screen.width / cols; var H = screen.height / rows; var item = 0; //item of the queue array for(i=0; i<rows; i++) { for(j=0; j<cols; j++) { window.open(queue[item],item,'width='+W+',height='+H+',toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left='+W*j+',top='+H*i+''); item++; //add 1 to item if(item >= queue.length) { break } //break out of loop once item reaches length of queue } } }
this loop would always create the perfect grid, which may not always be what you want, if you have an odd number of elements, the last line should be missing a few cells, but this loop-ina-loop will create empty pop-ups to complete grid, so we add this last line to break out of the loop when the elements> = queue.length (that is, as soon as you reach the end of your queue)
UPDATE : here the loop is in reverse order (slightly easier to read here than in the comment)
for(i=rows-1; i>=0; i--) { for(j=cols-1; j>=0; j--) {
source share