Skip Navigation
Madison, Wisconsin
Powderkeg Web Design
September 5, 2017

Web Dev Tid Bit (WDTB): Bootstrap Carousel Animated Height

Nick
Nick
Web Dev Tid Bit (WDTB): Bootstrap Carousel Animated Height

The Bootstrap framework has a neat little carousel built in to it that I find myself using on almost every new website one form or another. The markup is pretty clean and it’s relatively easy to manipulate for customization. There is, however, 1 thing about it that I never really liked: If you have slides that are different heights and they are NOT in a fixed height container you will end up with a jumpy transition as the container expands or shrinks to the size of the new slide. Imagine the first slide below is on the screen and you slide a much shorter one. The overall height of the container is going to shrink causing the content jump suddenly:

 

Adding a specific container height and making sure the content always fits that is one way to do things, but that’s not a very good solution across the board. It turns out Bootstrap Carousel has some built in Javascript events that are triggered during and after slides that you can hook in to in order to animate this height change. Simple add this javascript snippet to your site:

<script>
//Animate any height differences
jQuery('#powderkeg_carousel').on('slide.bs.carousel', function (e) {
   var nextH = jQuery(e.relatedTarget).height();
   jQuery(this).find('.active.item').parent().animate({
      height: nextH
   }, 500);
});
</script>

This finds the next slide as the carousel is in the sliding transition, calculates the height of it, and uses the jQuery animate() function to give it a nice and smooth animation.

Here’s a link to a Codepen example.

Nick Kalscheur

Nick Kalscheur

Lead Developer