Multi-Column Grid with adjustable number of columns based on window width

Hi, I have question about multi-column grid with div-s of different heights (positioned absolute). JavaScript is used to set offsets top and offset left within the main container. I tried to set the number of columns to depend on the width of the window (onresize) but it doesn’t work the way I did it.

Could anyone help? Thank you.


<body>
<div id="grid_container">
    <div style="height: 140px;"><div>1</div></div>
    <div style="height: 200px;"><div>2</div></div>
    <div style="height: 120px;"><div>3</div></div>
    <div style="height: 180px;"><div>4</div></div>
    <div style="height: 150px;"><div>5</div></div>
    <div style="height: 160px;"><div>6</div></div>
    <div style="height: 180px;"><div>7</div></div>
    <div style="height: 170px;"><div>8</div></div>
    <div style="height: 160px;"><div>9</div></div>
    <div style="height: 180px;"><div>10</div></div>
    <div style="height: 150px;"><div>11</div></div>
    <div style="height: 160px;"><div>12</div></div>
    <div style="height: 130px;"><div>13</div></div>
    <div style="height: 140px;"><div>14</div></div>
    <div style="height: 210px;"><div>15</div></div>
</div>
</body>


window.addEventListener('load', renderGrid, false);
window.addEventListener('resize', renderGrid, false);

function renderGrid(){
			
	var blocks = document.getElementById("grid_container").children;
	var pad = 10, cols, newleft, newtop;
		
	if(window.innerWidth<400){
		cols = 2;
	}
	else{
		cols = 3;
	}
	
			
	for(var i=1; i<blocks.length; i++){
			
		if(i % cols == 0){
			newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad;
			blocks[i].style.top = newtop + "px";
		}
		else{
			if(blocks[i-cols]){ 				
				newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad;
				blocks[i].style.top = newtop + "px";
			}
			
			newleft = (blocks[i-1].offsetLeft + blocks[i-1].offsetWidth) + pad;
			blocks[i].style.left = newleft + "px";
				
		}		
	}
}