Twitter Bootstrap is awesome. The amount of grunt work that Bootstrap makes easy is amazing. One of Bootstrap’s great features is animated carousels; they are a nice way to display a lot of information without taking up a lot of vertical height. With Bootstrap, we just wrap our content in a couple of divs, and before we know it we have a nice scolling carousel.

One thing that I don’t like about Bootstrap’s carousel implementation is that it dynamically resizes the carousel’s height based on the size of the content currently being displaying. If all your content is exactly the same height this isn’t such a big deal, but if it’s not you end up with page elements below the carousel jumping around as the carousel resizes. This seems like terrible UX to me.

Thankfully this is not all that difficult to fix. In just a few lines of JavaScript/jQuery, we can scan through the carousel slides and determine the height of the tallest slide, and use its height for all of them. The code is pretty straightforward:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function carouselNormalization() {
  var items   = $('#carousel-id .item'),              // grab all the slides
      heights = [],                                   // array to store heights
      tallest;                                        // tallest slide

  if (items.length) {
    function normalizeHeights() {
      items.each(function() {
        heights.push($(this).height());               // add each slide's height
      });                                             // to the array

      tallest = Math.max.apply(null, heights);        // find the largest height

      items.each(function() {
        $(this).css('min-height', tallest + 'px');    // set each slide's minimum
      });                                             // height to the largest
    };

    normalizeHeights();

    $(window).on('resize orientationchange', function() {
      tallest = 0, heights.length = 0;               // reset the variables

      items.each(function() {
        $(this).css('min-height', '0');              // reset each slide's height
      });

      normalizeHeights();                            // run it again
    });
  }
}

Call that in a document.ready block:

[Edit: Calling this on window.onload will wait until all the assets have been loaded so a maximum height can be calculated correctly.]

1
2
3
window.onload = function() {
  carouselNormalization();
}

and your page elements will stop jumping around.

H/T to Eddie Staples’s post for providing the basic JavaScript.

Comments