Joined April 2015
·

Damià Rita Espada

Spain
·

I made another version that worked better for me. This one fixes the height of the carousel div to such a height that the biggest image fits in it.

Note that I use a custom way to measure images because, when they are hidden, they sometimes are 0px.

This version supports multiple carousel in one document and does not assume one 'id' is used


function normalizeSizesAllCarousels(){ jQuery('.carousel.slide').each(function(){//we loop all the present carousels normalizeSizesOneCarousel('#' + jQuery(this).attr('id')); }); } function normalizeSizesOneCarousel(idSelectorCarousel){ var images=jQuery(idSelectorCarousel + ' .carousel-inner .item img'); var availableWidht=jQuery(idSelectorCarousel).innerWidth(); var maxHeight=0; var imageHeight=0; var aspectRatio=1;//width/height images.each(function(){ aspectRatio=calcImgWidth(this)/calcImgHeight(this); imageHeight=availableWidht/aspectRatio; if(imageHeight>maxHeight){maxHeight=imageHeight;} }); jQuery(idSelectorCarousel).height(maxHeight); } function calcImgWidth(img){ var width=img.width; if (width>0){ return width; }else{ jQuery('body').append('<div id="tempContainer" style="visibility:hidden;position:absolute"></div>'); jQuery('#tempContainer').append(img.clone().attr('id',false)); width= jQuery('#tempContainer img').width; jQuery('#tempContainer').remove(); return width; } } function calcImgHeight(img){ var height=img.height; if (height>0){ return height; }else{ jQuery('body').append('<div id="tempContainer" style="visibility:hidden;position:absolute"></div>'); jQuery('#tempContainer').append(img.clone().attr('id',false)); height= jQuery('#tempContainer img').height; jQuery('#tempContainer').remove(); return height; } } jQuery(document).ready(function(){normalizeSizesAllCarousels();}); jQuery(window).on('resize orientationchange', function () {normalizeSizesAllCarousels();}); </code> </pre>
Achievements
1 Karma
0 Total ProTip Views