|
| 1 | +/** |
| 2 | + * Copyright IBM Corp. 2016, 2018 |
| 3 | + * |
| 4 | + * This source code is licensed under the Apache-2.0 license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * Utility that sets an array of elements to the same height. |
| 10 | + * |
| 11 | + * @example |
| 12 | + * import {sameheight} from '@carbon/ibmdotcom-utilities'; |
| 13 | + * |
| 14 | + * sameheight(ElementArray, 'md'); |
| 15 | + * |
| 16 | + * if you want the utility to refresh the sizes as you resize the screen, consider using a listener: |
| 17 | + * window.addEventListener('resize', sameheight(ElementArray, 'md')); |
| 18 | + * |
| 19 | + * @param {Array} elemCollection Html objects array |
| 20 | + * @param {string} minSize Minimum size for the utility to be activated, empty for small, |
| 21 | + * md for medium, lg for large, xlg for xlarge, max for maximum |
| 22 | + */ |
| 23 | +function sameHeight(elemCollection, minSize = false) { |
| 24 | + const elemArr = Array.prototype.slice.call(elemCollection); |
| 25 | + let targetWidth = 0; |
| 26 | + if (minSize) { |
| 27 | + switch (minSize) { |
| 28 | + case 'md': |
| 29 | + targetWidth = 671; |
| 30 | + break; |
| 31 | + case 'lg': |
| 32 | + targetWidth = 1055; |
| 33 | + break; |
| 34 | + case 'xlg': |
| 35 | + targetWidth = 1311; |
| 36 | + break; |
| 37 | + case 'max': |
| 38 | + targetWidth = 1583; |
| 39 | + break; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + if (window.innerWidth > targetWidth) { |
| 44 | + elemArr.forEach(elem => { |
| 45 | + elem.style.height = 'auto'; |
| 46 | + }); |
| 47 | + let targetHeight = 0; |
| 48 | + |
| 49 | + elemArr.forEach(elem => { |
| 50 | + elem.offsetHeight > targetHeight |
| 51 | + ? (targetHeight = elem.offsetHeight) |
| 52 | + : false; |
| 53 | + }); |
| 54 | + |
| 55 | + elemArr.forEach(elem => { |
| 56 | + elem.offsetHeight == targetHeight; |
| 57 | + elem.style.height = targetHeight + 'px'; |
| 58 | + }); |
| 59 | + } else { |
| 60 | + elemArr.forEach(elem => { |
| 61 | + elem.style.height = 'auto'; |
| 62 | + }); |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +export default sameHeight; |
0 commit comments