While working on a Bootstrap-based project, we needed the heights of all the carousel items to be the same height, even though the content was of different heights.
Bootstrap uses position:absolute
to move the items. As such, techniques like flex and grid aren’t of much help here.
The top result on Google as of this writing works but only using Jquery. A lot of people were asking for this in Vanilla Javascript, so we created a version that worked without Jquery.
If anyone finds this useful or has any questions feel free to reach out on Facebook or Instagram.
function normalizeSlideHeights() {
var reviewCarousels = document.querySelectorAll('#reviewCarousel');
for (var i = 0; i < reviewCarousels.length; i++) {
var items = reviewCarousels[i].querySelectorAll('.carousel-item');
// reset the height
for (var j = 0; j < items.length; j++) {
items[j].style.minHeight = '0';
items[j].style.height = 'auto';
}
// set the height
var maxHeight = 0;
for (var k = 0; k < items.length; k++) {
var itemClone = items[k].cloneNode(true);
itemClone.style.display = 'block';
reviewCarousels[i].appendChild(itemClone);
var itemHeight = itemClone.offsetHeight;
reviewCarousels[i].removeChild(itemClone);
if (itemHeight > maxHeight) {
maxHeight = itemHeight;
}
}
console.log(maxHeight);
for (var l = 0; l < items.length; l++) {
items[l].style.height = maxHeight + 'px';
}
}
}
window.addEventListener('load', normalizeSlideHeights);
window.addEventListener('resize', normalizeSlideHeights);
window.addEventListener('orientationchange', normalizeSlideHeights);