Arrange grid elements into tiles. Works great if most of your columns match in width, and if you keep your wider ones on top...
(function ($) { | |
'use strict'; | |
$.fn.wmTiles = function () { | |
var container = $(this), | |
tiles = container.children(), | |
arrange = function () { | |
var places = [{ | |
t: 0, | |
l: 0, | |
w: container.width() | |
}], | |
p = 0, | |
n, | |
updateIndexes = function () { | |
var i; | |
for (i = 0; i < places.length; i += 1) { | |
if (i === 0 || places[i].t < places[p].t) { | |
p = i; | |
} | |
} | |
switch (p) { | |
case 0: | |
n = p + 1; | |
break; | |
case places.length - 1: | |
n = p - 1; | |
break; | |
default: | |
n = places[p + 1].t < places[p - 1].t ? p + 1 : p - 1; | |
} | |
}, | |
fit = function (tile) { | |
var w = $(tile).outerWidth(), | |
h = $(tile).height(); | |
if (w < places[p].w + 3) { | |
if (w < places[p].w) { | |
places.splice(p + 1, 0, { | |
t: places[p].t, | |
l: places[p].l + w, | |
w: places[p].w - w | |
}); | |
places[p].w = w; | |
} | |
$(tile).css({ | |
position: 'absolute', | |
top: places[p].t, | |
left: places[p].l | |
}); | |
places[p].t += h; | |
if (places[p].t > container.height()) { | |
container.height(places[p].t); | |
} | |
updateIndexes(); | |
return true; | |
} | |
return false; | |
}, | |
merge = function () { | |
places[n].w += places[p].w; | |
places[n].l = places[(p < n) ? p : n].l; | |
places.splice(p, 1); | |
updateIndexes(); | |
}; | |
tiles.removeAttr('style'); | |
if (tiles.css('float') === 'left') { | |
container.height(0); | |
$.map(tiles, function (tile) { | |
while (!fit(tile)) { merge(); } | |
}); | |
} else { | |
container.height('auto'); | |
} | |
}; | |
container.css({ position: 'relative' }); | |
arrange(); | |
$('img', container).load(arrange); | |
$(window).resize(arrange); | |
}; | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment