function carouselNormalization() sometimes works and sometimes doesn't work

Viewed 24

I used a function to equalize the height of all images to the tallest image in a bootstrap carousel, so that the rest of the content doesn't jump around.

Sometimes the function gets the height of the elements and sometimes not. It seems to be kind of a coincidence what happens. When it doesn't catch any height, it just applies 0 as max height, so nothing is won.

The function takes the height of all images, calculates the tallest and applies this height on all images.

It is a function from this page: http://ryanringler.com/blog/2014/08/24/fixed-height-carousel-for-twitter-bootstrap

And also dicussed here: Twitter Bootstrap carousel different height images cause bouncing arrows

Why would this just work sometimes? What did I miss?

  var items = $("#carouselExampleControls .carouselImg"), //grab all slides
    heights = [], //create empty array to store height values
    tallest; //create variable to make note of the tallest slide
  if (items.length) {
    function normalizeHeights() {
      items.each(function() { //add heights to array
        heights.push($(this).height());
      });
      tallest = Math.max.apply(null, heights); //cache largest value
      items.each(function() {
        $(this).css('min-height', tallest + 'px');
      });
    };
    normalizeHeights();
    $(window).on('resize orientationchange', function() {
      tallest = 0, heights.length = 0; //reset vars
      items.each(function() {
        $(this).css('min-height', '0'); //reset min-height
      });
      normalizeHeights(); //run it again 
    });
  }
}

/**
 * Wait until all the assets have been loaded so a maximum height 
 * can be calculated correctly.
 */
window.onload = function() {
  carouselNormalization();
} 

I also call the function in another function that is triggered after a click (loads detailpage of clicked product including the carousel and its images)

0 Answers
Related