Last active
October 27, 2018 16:07
-
-
Save monkishtypist/67c72632979d3357339ec08316c0390e to your computer and use it in GitHub Desktop.
Set Bootstrap carousel item heights
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Set Carousel Item heights | |
* | |
* The following jQuery sets the height of each `.carousel-item` | |
* to the height of the largest carousel item in the set. This | |
* prevents unusual resizing issues for dynamic text lengths. | |
*/ | |
(function($) { | |
function setCarouselHeight($carousel) { | |
var id = $carousel.attr("id"); | |
var maxCarouselItemHeight = Math.max.apply(null, $carousel.find(".carousel-item").map(function (){ | |
return $(this).height(); | |
}).get()); | |
$carousel.find(".carousel-item").each(function(){ | |
$(this).css("height", maxCarouselItemHeight); | |
}); | |
} | |
var $carousels = $(".carousel"); | |
$carousels.each(function(){ | |
setCarouselHeight($(this)); | |
}); | |
$(window).resize(function(){ | |
$carousels.each(function(){ | |
$(this).find(".carousel-item").each(function(){ | |
$(this).css("height", ""); | |
}); | |
setCarouselHeight($(this)); | |
}); | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I frequently use Bootstrap Carousels in builds as a content slider, for example for testimonials. By default however the carousel height is not fixed and resizes based on the content. Since content length can differ from slide to slide, this causes page jumping and the last line of text can appear to be clipped momentarily while sliding in.
To fix this, I use this jQuery to calculate the height of the largest slide and apply that height to all other slides essentially creating a fixed height carousel.