Equal Height for All Elements Using Vanilla JavaScript

on in JavaScript DOM | Last modified on

In my ImagePress plugin, we needed to ensure that all boxes have the same height after they have been loaded.

Given the following DOM structure:

<div class="ip-list">
    <div class="ip-box">my content here</div>
    <div class="ip-box">my content here</div>
    <div class="ip-box">my content here</div>
</div>

I used the following function:

function equalHeight(containerSelector) {
    const elements = document.querySelectorAll(containerSelector);
    let currentTallest = 0;
    let currentRowStart = 0;
    let rowDivs = [];
    let topPosition = 0;

    elements.forEach(function(el) {
        el.style.height = 'auto';
        topPosition = el.offsetTop;

        if (currentRowStart !== topPosition) {
            rowDivs.forEach(function(rowEl) {
                rowEl.style.height = currentTallest + 'px';
            });
            rowDivs = [];
            currentRowStart = topPosition;
            currentTallest = el.offsetHeight;
            rowDivs.push(el);
        } else {
            rowDivs.push(el);
            currentTallest = Math.max(currentTallest, el.offsetHeight);
        }
    });

    // Set the height for the last row
    rowDivs.forEach(function(rowEl) {
        rowEl.style.height = currentTallest + 'px';
    });
}

window.addEventListener('load', function() {
    equalHeight('.ip-list .ip-box');
});

window.addEventListener('resize', function() {
    equalHeight('.ip-list .ip-box');
});

This function ensures that all elements with the class .ip-box within .ip-list have equal heights, adjusting dynamically on window load and resize events.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *