Fix matchHeights in Owl Carousel on browser resize

  • Page Owner: Not Set
  • Last Reviewed: 2018-11-07

I've got a carousel where every carousel item needs to be the same size. Furthermore, each carousel item has an image and a div of text, those also need to be the same size.

Currently, owl carousel is used to make the carousel and the matchHeights library is used to make sure every item is the same height. The problems happen on resize. Both owl and match heights make calculations on resize, and if the match heights calculations happen first, the owl carousel item resize will ruin the calculated heights. What are some solutions to ensure that the heights remain in sync, even on browser resize?

<div class="carousel">
    <div class="carousel-item">
        <div class="col-1">
            Some Text
        </div>
        <div class="col-2" style="background-image: url(/foo/bar.jpg)">
        </div>
    </div>
</div>

Additional Posts

Obligatory I didn't test this. Use the "apply" function to avoid the automatic update functionality https://github.com/liabru/jquery-match-height#manually-apply-match-height and apply it after owl carousel resize event.

// Vars
var carouselVar = $('.carousel'),
    carouselItem = carouselVar.find('.carousel-item');
    
// Initialize matchHeight using the apply function
$.fn.matchHeight._apply(carouselItem);
    
carouselVar.owlCarousel({
    // ... owl options
}).on('resized.owl.carousel', function(){
	// Manually call matchHeight after screen resize
    $.fn.matchHeight._apply(carouselItem);
});

I have triggered an matchHeight update after Owl's resized event triggers. We did that on Florida DEM, I believe:

// Match height after carousel resizes
owl.on('resized.owl.carousel', function(e){
    $('.owl-carousel .target-class-here').matchHeight();
});

Initializing matchHeight with _apply as well, like Marshall mentioned, seems like a nice improvement. Less extra processing.

How I ended up solving this was a bit of a rethinking of how the carousel worked. I wanted to end the reliance on javascript to match the heights of the two boxes, thereby eliminating the multiple matchHeight() calls. In order to do this I had to switch the display attributes of the columns and the carousel items to flex.

.carousel {
    display: flex;
}
.carousel-item {
    display: flex;
}

Doing this reduced my javascript load and will prevent the need to recalculate the height on resize.