Normalize Bootstrap Carousel Item Heights

In working on a Bootstrap-based client project, they needed the heights of all the 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 on one carousel. In an attempt to rewrite the script to work with all carousels on a page, I realized that there was a way to simplify the entire script.

function normalizeSlideHeights() {
    $('.carousel').each(function(){
      var items = $('.carousel-item', this);
      // reset the height
      items.css('min-height', 0);
      // set the height
      var maxHeight = Math.max.apply(null, 
          items.map(function(){
              return $(this).outerHeight()}).get() );
      items.css('min-height', maxHeight + 'px');
    })
}

$(window).on(
    'load resize orientationchange', 
    normalizeSlideHeights);

The original script had a bunch of .each calls that weren’t necessary because jQuery already loops through all items when using methods like .css(). Also, I took advantage of map to avoid an extra loop and used get to convert that into an array that I could run Math.max on.

I’m not sure that orientationchange is necessary since my assumption is that a resize event would also fire but I haven’t tested it and since it was in the original script, I kept it in mine.

Published August 02, 2018
Categorized as JavaScript
Short URL: https://snook.ca/s/1128