javascript equal height blocks

Works in all modern browsers and IE9+.

javascript:

function heightsEqualizer(selector) {
    var elements = document.querySelectorAll(selector),
        max_height = 0,
        len = 0,
        i;
 
    if ( (elements) && (elements.length > 0) ) {
        len = elements.length;
 
        for (i = 0; i < len; i++) { // get max height
			elements[i].style.height = ''; // reset height attr
            if (elements[i].clientHeight > max_height) {
                max_height = elements[i].clientHeight;
            }
        }
 
        for (i = 0; i < len; i++) { // set max height to all elements
            elements[i].style.height = max_height + 'px';
        }
    }
}
 
if (document.addEventListener) {
    document.addEventListener('DOMContentLoaded', function() {
        heightsEqualizer('.js-equal-height');
    });
	window.addEventListener('resize', function(){
		heightsEqualizer('.js-equal-height');
	});
}
 
setTimeout(function () { // set 1 second timeout for having all fonts loaded
	heightsEqualizer('.js-equal-height');
}, 1000);

html:

<div class="blocks">
    <div class="block js-equal-height">Lorem Ipsum text.<br />
        Lorem Ipsum text.<br />
    </div>
    <div class="block js-equal-height">Lorem Ipsum text.<br />
        Lorem Ipsum text.<br />
        Lorem Ipsum text.<br />
        Lorem Ipsum text.<br/> 
    </div>
    <div class="block js-equal-height">Lorem Ipsum text.<br />
        Lorem Ipsum text.<br />
        Lorem Ipsum text.<br />
    </div>
    <div class="block js-equal-height">Lorem Ipsum text.<br />
        Lorem Ipsum text.<br />
        Lorem Ipsum text.<br />
        Lorem Ipsum text.<br/> 
        Lorem Ipsum text.<br/> 
    </div>
</div>

css:

* {
    box-sizing: border-box;
}
 
.blocks {
    float: left;
    width: 100%;
}
.block {
    float: left;
    width: 20%;
    background: #ffa;
    padding: 10px;
    margin: 10px;
}

2 comments on “javascript equal height blocks

  1. Vaibhavi

    After an entire day of searching, finally found the solution. Thanks :) Works wonderfully with DOM content.

Leave a Reply

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