This script looks for a data attribute applied to elements within a specified wrapper. It then sets all elements with the attribute to the same height (height of tallest div). I needed to add a wait time as the script would sometimes get the heights of the divs before the page had fully rendered. Even though the await is set to 0, it works.
There is also an event listener to listen for resize, and adjust the elements as they change size.
I have only been coding JS for a few weeks so I am not great at it.
HTML
<div id="div1">
<div data-equalize>
<p>Some content</p>
</div>
<div data-equalize>
<p>Some content</p>
</div>
<div data-equalize>
<p>Some content</p>
</div>
<div data-equalize>
<p>Some content</p>
</div>
</div>
Script
function equalizer(wrap) {
const equalizeEls = Array.from(wrap.querySelectorAll(`[data-equalize]`));
const wait = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));
//get the largest height in the array
function getLargestNumber(arr) {
return Math.max(...arr);
}
//get an array of heights
function getTallest(arr) {
const allheights = arr.map(x => x.clientHeight);
return getLargestNumber(allheights)
}
function equalizeHeights(els) {
const largest = getTallest(els);
return els.forEach(el => {
el.style.minHeight = `${largest}px`
});
}
async function handleResize() {
await wait(0); //needs a await to ensure page is fully loaded
equalizeHeights(equalizeEls)
}
window.addEventListener('DOMContentLoaded', handleResize);
window.addEventListener('resize', handleResize);
}
Running the script
new equalizer(document.querySelector(`#div1`))