Created
May 16, 2013 17:06
-
-
Save mduvall/5593330 to your computer and use it in GitHub Desktop.
An example of the Pinterest waterfall layout.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var generateRandomBoxes = function() { | |
var $doc = $(".container"); | |
var $bareBox = $("<div class='box' style='position:absolute; border:1px solid black; width:50px;'></div>"); | |
var maxHeight = 200; | |
var height, | |
$box; | |
for (var i = 0; i < 100; i++) { | |
height = Math.floor(Math.random() * maxHeight); | |
$box = $bareBox.clone().css('height', height + 'px') | |
$doc.append($box); | |
} | |
}; | |
var placeBoxes = function() { | |
var $boxes = $('.box'); | |
var screenWidth = $('.container').width(); | |
var columnWidth = 60; | |
// Initialize column array to 0 | |
var numColumns = Math.floor(screenWidth / columnWidth); | |
var columns = []; | |
var minIndex, | |
$box; | |
while (numColumns--) { | |
columns.push(0); | |
} | |
// Iterate over all the boxes and put it into the smallest column | |
for (var i = 0; i < $boxes.length; i++) { | |
$box = $($boxes[i]); | |
minIndex = 0; | |
for (var j = 0; j < columns.length; j++) { | |
if (columns[j] < columns[minIndex]) { | |
minIndex = j; | |
} | |
} | |
$box.css('left', minIndex * columnWidth); | |
$box.css('top', columns[minIndex]); | |
columns[minIndex] += $box.height(); | |
} | |
} | |
$(document).ready(function() { | |
generateRandomBoxes(); | |
placeBoxes(); | |
}); | |
$(window).resize(function() { | |
placeBoxes(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment