-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathequalizer.js
105 lines (94 loc) · 3.04 KB
/
equalizer.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
95
96
97
98
99
100
101
102
103
104
105
const dimension = {
WIDTH: 'width',
MIN_WIDTH: 'minWidth',
HEIGHT: 'height',
MIN_HEIGHT: 'minHeight',
};
/**
* Equalizes the dimension of the specified elements.
*
* @param elements Elements to be equalized
* @param d Dimension
* @param [d2=d] Dimension that should be set
*/
function equalizeDimensions(elements, d, d2) {
const { length } = elements;
const dimensionToSet = d2 || d;
let max = 0;
if (length > 1) {
let currentDim;
for (let i = 0; i < length; i += 1) {
currentDim = Math.ceil(elements[i].getBoundingClientRect()[d]);
// find maximum dimension
if (max < currentDim) {
max = currentDim;
}
}
if (max > 0) {
// set all elements to max dimension
for (let i = 0; i < length; i += 1) {
const element = elements[i];
element.style[dimensionToSet] = `${max}px`;
}
}
}
}
/**
* Equalizer
* To equalize the height/width of different html elements, you have to give them the attributes "data-cc-equalize-width", "data-cc-equalize-height"
* or "data-cc-equalize-both". The value of the attributes has to be an id which all of the elements that should be equalized have. Also, you have to
* set this id to the attribute "data-cc-equalize" on a common parent element.
*
* @param {HTMLElement} element - optional root node of the elements that should be equalized
*/
export default function equalizer(element) {
const parents = Array.prototype.slice.call(
(element || document).querySelectorAll(
'[data-cc-equalize], [data-equalize]'
)
);
if (
element &&
(element.hasAttribute('data-cc-equalize') ||
element.hasAttribute('data-equalize'))
) {
parents.push(element);
}
for (let i = 0, l = parents.length; i < l; i += 1) {
const parent = parents[i];
const equalizeId =
parent.getAttribute('data-cc-equalize') ||
parent.getAttribute('data-equalize') ||
'';
// equalize width
let elements = parent.querySelectorAll(
`[data-cc-equalize-width="${equalizeId}"]`
);
if (elements.length) {
equalizeDimensions(elements, dimension.WIDTH, dimension.MIN_WIDTH);
}
// equalize height
elements = parent.querySelectorAll(
`[data-cc-equalize-height="${equalizeId}"]`
);
if (elements.length) {
equalizeDimensions(
elements,
dimension.HEIGHT,
dimension.MIN_HEIGHT
);
}
// equalize both
elements = parent.querySelectorAll(
`[data-cc-equalize-both="${equalizeId}"]`
);
if (elements.length) {
equalizeDimensions(elements, dimension.WIDTH, dimension.MIN_WIDTH);
equalizeDimensions(
elements,
dimension.HEIGHT,
dimension.MIN_HEIGHT
);
}
}
}