Create a carousel with three slides

Description: Make a carousel with three slides, previous and next buttons and three indicators.

Hint:

  • Use carousel slide, carousel-inner, carousel-item active and the control buttons with data-bs-slide.

Solution

<div id="cx" class="carousel slide" style="max-width: 420px">
  <div class="carousel-indicators">
    <button type="button" data-bs-target="#cx" data-bs-slide-to="0" class="active" aria-label="Slide 1"></button>
    <button type="button" data-bs-target="#cx" data-bs-slide-to="1" aria-label="Slide 2"></button>
    <button type="button" data-bs-target="#cx" data-bs-slide-to="2" aria-label="Slide 3"></button>
  </div>
  <div class="carousel-inner">
    <div class="carousel-item active"><img src="images/photo.jpg" class="d-block w-100" alt="Slide 1"></div>
    <div class="carousel-item"><img src="images/photo.jpg" class="d-block w-100" alt="Slide 2"></div>
    <div class="carousel-item"><img src="images/photo.jpg" class="d-block w-100" alt="Slide 3"></div>
  </div>
  <button class="carousel-control-prev" type="button" data-bs-target="#cx" data-bs-slide="prev"><span class="carousel-control-prev-icon" aria-hidden="true"></span><span class="visually-hidden">Previous</span></button>
  <button class="carousel-control-next" type="button" data-bs-target="#cx" data-bs-slide="next"><span class="carousel-control-next-icon" aria-hidden="true"></span><span class="visually-hidden">Next</span></button>
</div>
Live preview

const cx = document.getElementById('cx');
const idx = () => [...cx.querySelectorAll('.carousel-item')].findIndex(i => i.classList.contains('active')) + 1;
cx.querySelector('.carousel-control-next').click();
await new Promise(r => setTimeout(r, 900));
console.log('after Next: slide ' + idx());
cx.querySelector('.carousel-control-next').click();
await new Promise(r => setTimeout(r, 900));
console.log('after Next again: slide ' + idx());
cx.querySelector('.carousel-control-next').click();
await new Promise(r => setTimeout(r, 900));
console.log('after Next at the end: slide ' + idx() + ' (it goes round)');
Console output (real Chrome)

after Next: slide 2
after Next again: slide 3
after Next at the end: slide 1 (it goes round)

How it works

  • Exactly one carousel-item must have the class active at the start.
  • After the last slide, the carousel goes back to the first one.

Read Carousel.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.