Bootstrap Carousel Auto Height Adjustment

Bootstrap Carousel Auto Height Adjustment

Auto Adjust Hero Banner Or Carousel Images to height at browser height

lets assume we have 3 DIVs above the Carousel

  1. Top Bar
  2. Head-div
  3. Carousel slider

Carousel should adjust its height with window according to subtracting all above height occupied by above DIVs

Html Look like

				
					    <div class="div1">This is TOP BAR.</div>
    <div class="div2">This is a HEADER DIV.</div>
  <!-- You can add banner OR slider  -->
    <div class="carousel">
        <img decoding="async" class="dynamic-image" src="https://via.placeholder.com/800x600?text=Image+1" alt="Image 1">
        <img decoding="async" class="dynamic-image" src="https://via.placeholder.com/800x600?text=Image+2" alt="Image 2">
        <img decoding="async" class="dynamic-image" src="https://via.placeholder.com/800x600?text=Image+3" alt="Image 3">
    </div>

				
			

With Jquery

				
					function adjustCarouselImagesHeight() {
    // Get the combined height of the first divs for exmple two divs
    var div1Height = $('.div1').outerHeight();
    var div2Height = $('.div2').outerHeight();
    
    // Calculate the remaining height for the images
    var remainingHeight = $(window).height() - (div1Height + div2Height);
    
    // Get all images in the carousel with the class 'dynamic-image'
    $('.dynamic-image').each(function() {
        // Set the height of each image
        $(this).css('height', remainingHeight + 'px');
    });
}

// Adjust the images' height when the page loads
$(document).ready(adjustCarouselImagesHeight);

// Adjust the images' height when the window is resized
$(window).resize(adjustCarouselImagesHeight);
				
			

With JavaScript

				
					function adjustCarouselImagesHeight() {
    // Get the combined height of the first two divs
    const div1Height = document.querySelector('.div1').offsetHeight;
    const div2Height = document.querySelector('.div2').offsetHeight;
    
    // Calculate the remaining height for the images
    const remainingHeight = window.innerHeight - (div1Height + div2Height);
    
    // Get all images in the carousel with the class 'dynamic-image'
    const images = document.querySelectorAll('.dynamic-image');
    
    // Loop through each image and set its height
    images.forEach(image => {
        image.style.height = `${remainingHeight}px`;
    });
}

// Adjust the images' height when the page loads
window.addEventListener('load', adjustCarouselImagesHeight);

// Adjust the images' height when the window is resized
window.addEventListener('resize', adjustCarouselImagesHeight);

				
			

Leave a Reply

Your email address will not be published. Required fields are marked *