-
Notifications
You must be signed in to change notification settings - Fork 0
/
minigrid.js
66 lines (58 loc) · 2.1 KB
/
minigrid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
(function(exports){
function minigrid(containerSelector, itemSelector, gutter, animate, done) {
var forEach = Array.prototype.forEach;
var containerEle = document.querySelector(containerSelector);
var itemsNodeList = document.querySelectorAll(itemSelector);
gutter = gutter || 6;
containerEle.style.width = '';
var containerWidth = containerEle.getBoundingClientRect().width;
var firstChildWidth = itemsNodeList[0].getBoundingClientRect().width + gutter;
var cols = Math.max(Math.floor((containerWidth - gutter) / firstChildWidth), 1);
var count = 0;
containerWidth = (firstChildWidth * cols + gutter) + 'px';
containerEle.style.width = containerWidth;
for (var itemsGutter = [], itemsPosX = [], g = 0; g < cols; g++) {
itemsPosX.push(g * firstChildWidth + gutter);
itemsGutter.push(gutter);
}
forEach.call(itemsNodeList, function(item){
var itemIndex = itemsGutter.slice(0).sort(function (a, b) {
return a - b;
}).shift();
itemIndex = itemsGutter.indexOf(itemIndex);
var posX = itemsPosX[itemIndex];
var posY = itemsGutter[itemIndex];
var transformProps = [
'webkitTransform',
'MozTransform',
'msTransform',
'OTransform',
'transform'
];
if (!animate) {
forEach.call(transformProps, function(transform){
item.style[transform] = 'translate(' + posX + 'px,' + posY + 'px)';
});
}
itemsGutter[itemIndex] += item.getBoundingClientRect().height + gutter;
count = count + 1;
if (animate) {
return animate(item, posX, posY, count);
}
});
var containerHeight = itemsGutter.slice(0).sort(function (a, b) {
return a - b;
}).pop();
containerEle.style.height = containerHeight + 'px';
if (typeof done === 'function'){
done();
}
}
if (typeof define === 'function' && define.amd) {
define(function() { return minigrid; });
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = minigrid;
} else {
exports.minigrid = minigrid;
}
})(this);