Well, you can do this in CSS for most browsers, so I would figure if you want to do with with javascript, you'd pretty much follow the same formula.
With CSS, you'd set a % width on your photo boxes, based on number per row. So if 5 in a row, width is something less than 20% (room for the margin).
Then initially everyone gets a margin. Let's say left margin.
With CSS you would count the items, and every nth item would NOT have the margin. So if there were 3 in a row, the first and every third after it, being the one on the left, would not have the left margin (like, in a ul, li:nth-child(3n+1).
You could use Javascript or jQuery to count through the items and either manually add in the appropriate CSS or have it add a class where your external stylesheet removed the margin.
So for example
Code:
$('#gallery li:nth-child(3n+1)').css(marginLeft, '0');
What Pinterest seems to do is use Javascript to manually place every single individual element using absolute positioning. I have no idea why someone would want to do it this way, but I have seen it on quite a few e-commerce sites, on pages showing multiple products. I think simply giving everyone a margin and then remove from whoever's on the edge is more elegant.
You could go further: calculate the width of the container with jQuery, divide it by the number of items per row, remove from that total however much total margin you want between elements, set that as the new element width, set the margins to your calculated margin width, and if you use percents you could have your elements growing and shrinking a bit to ensure they are always absolutely filling all the space, if your container is flexible to the viewport.
Bookmarks