/*! pinto jquery plugin @name pinto.js @description lightweight and customizable jquery plugin for creating pinterest like responsive grid layout @author max lawrence @version 1.0.0 @date 08.05.2015 @category jquery plugin @copyright (c) 2015 max lawrence (http://www.topbits.net) @license licensed under the mit (http://www.opensource.org/licenses/mit-license.php) license. */ (function($){ 'use strict'; var defaultoptions = { itemselector: '> div', // block identificator; itemwidth: 220, // width of one grid block in pixels; marginx: 10, // width spacing between blocks in pixels; marginy: 10, // height spacing between blocks in pixels; align: 'left', // blocks alignment - 'left', 'right' or 'center'; fitwidth: true, // adjusts block width to create optimal layout based on container size; animate: true, // css animation when updating layout; autoresize: true, // updates layout after browser is resized; resizedelay: 50 // time in milliseconds between browser resize and layout update; }; $.fn.pinto = function(options) { var $this = $(this), settings = $.extend(defaultoptions, options); $this.css('position', 'relative'); var getsmallestindex = function (a) { var index = 0; for (var i = 1, len = a.length; i < len; i++) { if (a[i] < a[index]) index = i; } return index; }; var dolayout = function (){ if (!$this.is(":visible")) { return; } var trans = (settings.animate ? 'top 0.5s, left 0.5s': 'none'), items = $this.find(settings.itemselector), width = $this.innerwidth(), marginx = parseint(settings.marginx || 0), marginy = parseint(settings.marginy || 0), itemwidth = settings.itemwidth, colscount = math.max(math.floor(width/(itemwidth + marginx)),1), cols = []; var i = colscount; while(i--) cols.push(0); var offset = 0; if(settings.fitwidth) { itemwidth += math.floor(0.5 + (width - (colscount * (itemwidth + marginx)))/colscount); } else { // calculate the offset based on the alignment of columns to the parent container if (settings.align === 'center') { offset += math.floor(0.5 + (width - (colscount * (itemwidth + marginx))) >> 1); } else if (settings.align === 'right') { offset += math.floor(0.5 + width - (colscount * (itemwidth + marginx))); }; }; items.each(function(index, item) { var $item = $(item), i = getsmallestindex(cols); $item.css({ position: 'absolute', top: cols[i] + marginy/2 + 'px', left: (itemwidth + marginx) * i + offset + 'px', width: itemwidth, margin: marginy/2 + 'px ' + marginx/2 + 'px', transition: trans }); cols[i] += $item.innerheight() + marginy; }); var height=0; i = colscount; while(i--) if(cols[i]>height) height = cols[i]; $this.css({height:height}); }; var onresizetimer = null; var onresize = function() { cleartimeout(onresizetimer); onresizetimer = settimeout(dolayout, settings.resizedelay); }; dolayout(); if (settings.autoresize) { var resize = $(window).on("resize", onresize); $this.on('remove', resize.unbind); }; }; })(window.jquery);