Pinterest Layout

(jQuery) Arrange divs of varying height on a page Pinterest-style

by Don Schaefer

CSS

#divMain {
    min-height: 50px;
}
.media {
    width: 150px;
    background-color: #ccc;
    margin: 15px;
    position: absolute;
}

JavaScript

$(document).ready(function () {
	/////////////////////////// SECTION 1
	
		//Create Initial Divs of Random Height For Testing Purposes
		for(i = 0; i < 10; i++) {
			var rHeight = Math.floor(Math.random() * (200 - 30 + 1)) + 30;
			var newDiv = document.createElement('div');
			document.body.appendChild(newDiv);
			$(newDiv).height(rHeight);
			$(newDiv).addClass('media');
		}
		
		//Initialize variables for placement of divs
		var winWidth = $(window).width();    
		var colWidth;
		var colCount;
		var colHeights = [];
		var divArray = [];
					
	/////////////////////////// SECTION 2
    
		//Find & store relevant properties of all divs
		var divLoop = 1;
		$('.media').each(function(){        
			var div = {
				width: $(this).width(),
				height: $(this).height(),
				margin: parseFloat($(this).css('margin').replace('px',''))
			};
			divArray.push(div);
			console.log("Div"+divLoop+" Height: "+$(this).height());
			divLoop++;
		});   
		
		//Assume all divs have the same width & margin, then store the total width of the first div in a variable we can use for calculating columns
		colWidth = divArray[0].width + divArray[0].margin; 
		
		//Determine # of columns to display based on available screen space
		colCount = Math.floor(winWidth/colWidth); 
		
		//Ensure there is always at least 1 column being displayed
		if(colCount < 1){colCount = 1;} 
				
		//Initially set all columnHeight values to 0
		for(i = 0; i < colCount; i++){
			colHeights.push(0);   
		}		
		
		// Function to get the Min value in Array
		Array.min = function (array) {			
			return Math.min.apply(Math, array);
		};
		
	
	/////////////////////////// SECTION 3
    
		//Place divs
		var currentCol = 0;    
		var currentDiv = 0;
		
		$('.media').each(function(){    
			//Loop through the different columns to figure out which column the div should go in        
			for(i = 0; i < (colCount); i++){
				//If the height of the current column is the lowest of all the...