skip to Main Content

I have a Bootstrap 4 carousel and I need to move 4 slides each time. I’m using this code, and it works:

$(this).carousel(4);

The problem is that the carousel just jumps to that index and doesn’t show any transitions. If I use $(this).carousel("next"); or $(this).carousel("prev"); it works and transitions correctly.

I tried use something like this:

$(this).carousel("next");
$(this).carousel("next");

But it does not work. Any help will be appreciated.

UPDATE

I found a workaround:

test = setInterval(() => {
  count++;
  $(".carousel-control-next").click();
  if (count > 3) {
    count = 0;
    clearInterval(test);
  }
}, 200);

I used an interval because the following does not work:

  • $(".carousel-control-next").click() inside a loop, or
  • $(".carousel-control-next").click() inside a setTimeout inside a loop

2

Answers


  1. first of all you need to include the required JavaScript and CSS in your project, create the necessary HTML and use build in carousel class.

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    

    link in the "head" and scripts in the end of "body".
    Then create the Carousel HTML using the carousel class and a unique IDs. The structure should include indicators, items, and nav controls:

    <div id="myCarousel" class="carousel slide" data-ride="carousel">
    
    
    <!-- Indic-->
      <ul class="carousel-indicators">
        <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
        <li data-target="#myCarousel" data-slide-to="1"></li>
        <li data-target="#myCarousel" data-slide-to="2"></li>
      </ul>
      
      <!-- slides -->
      <div class="carousel-inner">
        <div class="carousel-item active">
          <img src="img1.jpg" alt="Image 1" width="100%" height="100%">
          <div class="carousel-caption">
            <h3>Image 1</h3>
            <p>Description 1</p>
          </div>
        </div>
        <div class="carousel-item">
          <img src="img2.jpg" alt="Image 2" width="100%" height="100%">
          <div class="carousel-caption">
            <h3>Image 2</h3>
            <p>Description 2</p>
          </div>
        </div>
        <div class="carousel-item">
          <img src="img3.jpg" alt="Image 3" width="100%" height="100%">
          <div class="carousel-caption">
            <h3>Image 3</h3>
            <p>Description 3</p>
          </div>
        </div>
      </div>
      
      <!-- Contr-->
      <a class="carousel-control-prev" href="#myCarousel" data-slide="prev">
        <span class="carousel-control-prev-icon"></span>
      </a>
      <a class="carousel-control-next" href="#myCarousel" data-slide="next">
        <span class="carousel-control-next-icon"></span>
      </a>
    </div>
    

    Swap "img1.jpg", "img2.jpg", and "img3.jpg" with the your image paths or links (urls) you want to use.
    And last thing, activate the carousel, bootstrap automatically activates the it when the data-ride="carousel" attribute is added to the main Carousel div element.
    Also you can check more info here: carousel bootstrap docs.

    Hope this helps and answers your question.

    Almost forgot:

    $(document).ready(function() {
      // Initialize the carousel
      $("#myCarousel").carousel({ interval: false });
    
      // Custom next function
      $(".carousel-control-next").click(function() {
        moveCarousel(4);
      });
    
      // Custom prev function
      $(".carousel-control-prev").click(function() {
        moveCarousel(-4);
      });
    
      // Move the carousel by the specified number of slides
      function moveCarousel(steps) {
        var currentIndex = $("#myCarousel .carousel-inner .carousel-item.active").index();
        var totalItems = $("#myCarousel .carousel-inner .carousel-item").length;
    
        var targetIndex = currentIndex + steps;
        if (targetIndex < 0) {
          targetIndex = 0;
        } else if (targetIndex >= totalItems) {
          targetIndex = totalItems - 1;
        }
    
        $("#myCarousel").carousel(targetIndex);
      }
    });
    

    To enable smooth transition effect modify code:

    // Move the carousel by the specified number of slides
    function moveCarousel(steps) {
      var currentIndex = $("#myCarousel .carousel-inner .carousel-item.active").index();
      var totalItems = $("#myCarousel .carousel-inner .carousel-item").length;
      var remainingSteps = steps;
    
      function moveOneStep() {
        var newIndex = currentIndex + (remainingSteps > 0 ? 1 : -1);
        if (newIndex < 0 || newIndex >= totalItems) {
          return;
        }
    
        $("#myCarousel").one("slid.bs.carousel", function() {
          remainingSteps -= (remainingSteps > 0 ? 1 : -1);
          if (remainingSteps !== 0) {
            moveOneStep();
          }
        });
    
        $("#myCarousel").carousel(newIndex);
        currentIndex = newIndex;
      }
    
      moveOneStep();
    }
    
    Login or Signup to reply.
  2. I am not sure why .carousel(4) doesn’t animate for you, it does on a basic example:

    <!-- https://getbootstrap.com/docs/4.6/getting-started/introduction/#starter-template -->
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
      </head>
      <body>
    
        <!-- https://getbootstrap.com/docs/4.6/components/carousel/#slides-only -->
        <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
          <div class="carousel-inner">
            <div class="carousel-item active"><svg class="bd-placeholder-img bd-placeholder-img-lg d-block w-100" width="200" height="100" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: First slide" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#777"></rect><text x="50%" y="50%" fill="#555" dy=".3em">First slide</text></svg></div>
            <div class="carousel-item"><svg class="bd-placeholder-img bd-placeholder-img-lg d-block w-100" width="200" height="100" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Second slide" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#666"></rect><text x="50%" y="50%" fill="#444" dy=".3em">Second slide</text></svg></div>
            <div class="carousel-item"><svg class="bd-placeholder-img bd-placeholder-img-lg d-block w-100" width="200" height="100" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Third slide" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#555"></rect><text x="50%" y="50%" fill="#333" dy=".3em">Third slide</text></svg></div>
            <div class="carousel-item"><svg class="bd-placeholder-img bd-placeholder-img-lg d-block w-100" width="200" height="100" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Fourth slide" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#777"></rect><text x="50%" y="50%" fill="#555" dy=".3em">Fourth slide</text></svg></div>
            <div class="carousel-item"><svg class="bd-placeholder-img bd-placeholder-img-lg d-block w-100" width="200" height="100" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Fifth slide" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#666"></rect><text x="50%" y="50%" fill="#444" dy=".3em">Fifth slide</text></svg></div>
            <div class="carousel-item"><svg class="bd-placeholder-img bd-placeholder-img-lg d-block w-100" width="200" height="100" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Sixth slide" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#555"></rect><text x="50%" y="50%" fill="#333" dy=".3em">Sixth slide</text></svg></div>
          </div>
        </div>
    
        <button onclick="$('#carouselExampleSlidesOnly').carousel(4)">Skip to fifth slide</button>
    
        <!-- jQuery and Bootstrap Bundle (includes Popper) -->
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
      </body>
    </html>

    Two notes:

    • .carousel(4) jumps to the slide at index 4 (i.e. the fifth slide), regardless of the current slide. If you want to jump 4 forward from the current slide, use

      let index = $(this).find(".active").index();
      $(this).carousel(index + 4);
      
    • The animation goes directly from the current slide to the target slide, skipping over any intermediate slides. If you want the animation to go through all the intermediate slides, have a look at @David NoHorizon’s answer.

    I noticed that calling .carousel("next") twice doesn’t work for me either (it only goes forward one slide).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search