OWL CAROUSEL 2 - RANDOM IMG DIMENSIONS

by bizamajig

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.css">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.theme.min.css">
<h1>Owl Carousel. Slides with random height</h1>

<fieldset>
  <legend>Information</legend>
  <p>Max images height: <b id="max-height"></b></p>
</fieldset>

<hr>

<h2>Vertical align</h2>
<div class="owl-carousel bg-contain">
  <img src="http://lorempixel.com/234/100/technics/1/"  />
  <img src="http://lorempixel.com/234/400/technics/2/"  />
  <img src="http://lorempixel.com/234/200/technics/9/"  />
  <img src="http://lorempixel.com/234/150/technics/10/" />
</div>

<hr>

<h2>Full Zoom small images</h2>
<div class="owl-carousel bg-cover">
  <img src="http://lorempixel.com/234/100/technics/1/"  />
  <img src="http://lorempixel.com/234/400/technics/2/"  />
  <img src="http://lorempixel.com/234/200/technics/9/"  />
  <img src="http://lorempixel.com/234/150/technics/10/" />
</div>

CSS

/* Main */
.owl-wrapper-outer {
  border: 1px solid red;
  font: 0/0 a;
  line-height: 0;
}

.owl-carousel .owl-item {
  background-position: 50% 50%;
  background-repeat: no-repeat;
}
.bg-contain .owl-item { background-size: contain }
.bg-cover .owl-item { background-size: cover }

.owl-carousel .owl-item img {
  height: auto;
  width: 100%;
  visibility: hidden;
}

/* Demo style */
body {
    margin: 20px;
}
hr {
    margin: 30px 0;
}

JavaScript

$(".owl-carousel").each(function () {
  var $this = $(this);

  $this.owlCarousel({
    afterUpdate: function () {
      updateSize($this);
    },
    afterInit: function () {
      updateSize($this);
    }
  });
});

function updateSize($carousel) {
  var maxHeight = 0;
    
  $('.owl-item', $carousel).each(function () {
    var $this = $(this);
    var $image = $this.find('img');

    //Max height
    var prevHeight = $this.height();
    var thisHeight = $this.height('auto').height();
    $this.height(prevHeight);
    maxHeight = (maxHeight > thisHeight ? maxHeight : thisHeight);

    //Set image as background
    var imageSource = $image.attr('src');
    $this.css('backgroundImage', 'url(' + imageSource + ')');
  });
  
  //Set equal height
  $('.owl-item', $carousel).height(maxHeight);

  $('#max-height').text(maxHeight + 'px');
}