How to use Vanilla JavaScript In Bootstrap
For create a fixed sliding carousel using vanilla JavaScript by initializing the carousel, handling indicators with event listeners, and implementing pause and resume on mouse hover. Ensure consistent image sizes for a cohesive display.
Example: Illustration of fixing sliding Carousel in Bootstrap 5 using vanilla JavaScript.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1" > < link href = "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel = "stylesheet" > < title >Fixed Sliding Carousel</ title > </ head > < body > < div class = "container mt-5" > < div id = "myCarousel" class = "carousel slide" data-bs-ride = "carousel" > < div class = "carousel-inner" > < div class="carousel-item active h-90"> < img src = "http://www.w3wiki.org/wp-content/uploads/gfg_200X200-1.png" class = "mx-auto d-block w-80" alt = "HTML" > </ div > < div class = "carousel-item h-90" > < img src = "https://media.w3wiki.org/wp-content/cdn-uploads/20190710102234/download3.png" class = "mx-auto d-block w-80" alt = "CSS" > </ div > </ div > < button class = "carousel-control-prev" type = "button" data-bs-target = "#myCarousel" data-bs-slide = "prev" > < span class="carousel-control-prev-icon bg-black rounded-circle" aria-hidden = "true" > </ span > < span class = "visually-hidden" >Previous</ span > </ button > < button class = "carousel-control-next" type = "button" data-bs-target = "#myCarousel" data-bs-slide = "next" > < span class="carousel-control-next-icon bg-black rounded-circle" aria-hidden = "true" > </ span > < span class = "visually-hidden" > Next </ span > </ button > </ div > </ div > < script src = "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" > </ script > < script > // Get carousel element var myCarousel = document.getElementById('myCarousel'); // Activate Carousel new bootstrap.Carousel(myCarousel); // Enable Carousel Indicators var carouselItems = document.querySelectorAll('.carousel-item'); carouselItems.forEach(function (item, index) { item.addEventListener('click', function () { new bootstrap.Carousel(myCarousel).to(index); }); }); // Pause the carousel when the mouse is over it myCarousel.addEventListener('mouseenter', function () { new bootstrap.Carousel(myCarousel).pause(); }); myCarousel.addEventListener('mouseleave', function () { new bootstrap.Carousel(myCarousel).cycle(); }); </ script > </ body > </ html > |
Output:
How to fix sliding Carousel in Bootstrap 5 ?
In Bootstrap 5, a Sliding Carousel is a dynamic component that displays a series of images or content sequentially. It enables a visually appealing, automatic, or user-triggered transition between slides. Users can navigate through the slides using controls, creating an interactive and engaging content display.
Table of Content
- Using Bootstrap and jQuery
- Using vanilla JavaScript