forked from Sam152/Javascript-Equal-Height-Responsive-Rows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrids.js
94 lines (88 loc) · 2.84 KB
/
grids.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* Javascript-Equal-Height-Responsive-Rows
* https://github.com/Sam152/Javascript-Equal-Height-Responsive-Rows
*/
(function($) {
'use strict';
/**
* Set all elements within the collection to have the same height.
*/
$.fn.equalHeight = function() {
var heights = [];
$.each(this, function(i, element) {
var $element = $(element);
var elementHeight;
// Should we include the elements padding in it's height?
var includePadding = ($element.css('box-sizing') === 'border-box') || ($element.css('-moz-box-sizing') === 'border-box');
if (includePadding) {
elementHeight = $element.innerHeight();
} else {
elementHeight = $element.height();
}
heights.push(elementHeight);
});
this.css('height', Math.max.apply(window, heights) + 'px');
return this;
};
/**
* Create a grid of equal height elements.
*/
$.fn.equalHeightGrid = function(columns) {
var $tiles = this.filter(':visible');
$tiles.css('height', 'auto');
for (var i = 0; i < $tiles.length; i++) {
if (i % columns === 0) {
var row = $($tiles[i]);
for (var n = 1; n < columns; n++) {
row = row.add($tiles[i + n]);
}
row.equalHeight();
}
}
return this;
};
/**
* Detect how many columns there are in a given layout.
*/
$.fn.detectGridColumns = function() {
var offset = 0,
cols = 0,
$tiles = this.filter(':visible');
$tiles.each(function(i, elem) {
var elemOffset = $(elem).offset().top;
if (offset === 0 || elemOffset === offset) {
cols++;
offset = elemOffset;
} else {
return false;
}
});
return cols;
};
/**
* Ensure equal heights now, on ready, load and resize.
*/
var grids_event_uid = 0;
$.fn.responsiveEqualHeightGrid = function() {
var _this = this;
var event_namespace = '.grids_' + grids_event_uid;
_this.data('grids-event-namespace', event_namespace);
function syncHeights() {
var cols = _this.detectGridColumns();
_this.equalHeightGrid(cols);
}
$(window).bind('resize' + event_namespace + ' load' + event_namespace, syncHeights);
syncHeights();
grids_event_uid++;
return this;
};
/**
* Unbind created events for a set of elements.
*/
$.fn.responsiveEqualHeightGridDestroy = function() {
var _this = this;
_this.css('height', 'auto');
$(window).unbind(_this.data('grids-event-namespace'));
return this;
};
})(window.jQuery);