Issue with displaying multiple carousels on a single page

I am encountering an issue with multiple carousels on the same page. Utilizing bootstrap for my carousels, I noted that the carousel functions properly when there is only one present. However, when there are other carousels on the page, the slider loop malfunctions. Removing one carousel resolves this issue, despite renaming both carousel wrapper IDs and binding them in jQuery. The problem persists...

CODEPEN

css

/* 
    Creative Commons 2.0 License - Attribution required
*/
@media (min-width: 768px) and (max-width: 991px) {
    /* Code by Azmind.com */
}
...

HTML

<!-- Top content 1-->
<div class="top-content">
...
</div>


<!-- Top content 2 -->
<div class="top-content">
...
</div>

jQuery

/*
    Carousel Functionality
*/
$('#carousel-example,#carousel-example-2').on('slide.bs.carousel', function (e) {
    /*
        CC 2.0 License - Attribution required
    */
    var $e = $(e.relatedTarget);
    var idx = $e.index();
    var itemsPerSlide = 5;
    var totalItems = $('.carousel-item').length;
 
    if (idx >= totalItems-(itemsPerSlide-1)) {
        // Append slides based on direction
    }
});

https://i.sstatic.net/sREUD.png

How can I ensure each carousel loops independently without impacting others?

Answer №1

$('.carousel-item') can be used to locate all items in every carousel.

To target the current carousel, you must include a reference like:

$(this).find('.carousel-item').length;

or

$('.carousel-item', this).length;

(both provide the same result but have different syntax)

The same approach can be applied for appendTo as well.

Updated excerpt:

/*
    Carousel
*/
$('#carousel-example,#carousel-example-2').on('slide.bs.carousel', function(e) {
  /*
      CC 2.0 License Iatek LLC 2018 - Attribution required
  */
  var $e = $(e.relatedTarget);
  var idx = $e.index();
  var itemsPerSlide = 5;
  var totalItems = $(this).find('.carousel-item').length;

  if (idx >= totalItems - (itemsPerSlide - 1)) {
    var it = itemsPerSlide - (totalItems - idx);
    for (var i = 0; i < it; i++) {
      // append slides to end
      if (e.direction == "left") {
        $('.carousel-item', this).eq(i).appendTo($('.carousel-inner', this));
      } else {
        $('.carousel-item', this).eq(0).appendTo($('.carousel-inner', this));
      }
    }
  }
});
// custom code by Iatek LLC 2018 - CC 2.0 License - Attribution required

@media (min-width: 768px) and (max-width: 991px) {
  /* Show 4th slide on md if col-md-4*/
  .carousel-inner .active.col-md-4.carousel-item+.carousel-item+.carousel-item+.carousel-item {
    position: absolute;
    top: 0;
    right: -33.3333%;
    z-index: -1;
    display: block;
    visibility: visible;
  }

// Additional media queries and styles...
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c4e4343585f585e4d5c6c18021c021c">[email protected]</a>/dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87e5e8e8f3f4f3f5e6f7c7b3a9b7a9b7">[email protected]</a>/dist/js/bootstrap.min.js"></script>


<!-- Sample content for carousels -->
<div class="top-content">
  <div class="container-fluid">
    <div id="carousel-example" class="carousel slide" data-ride="carousel">
      <div class="carousel-inner row w-100 mx-auto" role="listbox">
         <!-- Include image items within the carousel -->
      </div>
       <!-- Addition carousel controls -->
    </div>
  </div>
</div>


<!-- More content for additional carousel -->
<div class="top-content">
  <div class="container-fluid">
    <div id="carousel-example-2" class="carousel slide" data-ride="carousel">
      <div class="carousel-inner row w-100 mx-auto" role="listbox">
        <!-- Add image items for the second carousel -->
          
      </div>
      <a class="carousel-control-prev" href="#carousel-example-2" role="button" data-slide="prev">
      
      <a class="carousel-control-next" href="#carousel-example-2" role="button" data-slide="next">
      
    </div>
  </div>
</div>

Answer №2

When working with the Bootstrap carousel, it is advisable to utilize its classes instead of the IDs in your jQuery carousel function. The same principle applies when using the Owl Carousel 2 - utilizing the ID for multiple carousels will only work for one, whereas using the same class will enable all carousels to function properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with HTML/CSS: rectangle doesn't scroll as expected

I'm in the process of developing a new website and I want to include a top bar and footer with some unique elements on it. Additionally, I am looking to create a rectangular area where I can input text. After writing the following code snippet, this ...

User authentication using .pre save process

I have an API that accepts users posted as JSON data. I want to validate specific fields only if they exist within the JSON object. For example, a user object could contain: { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

PHP is throwing an error because of a missing parenthesis in the argument list

Displaying data from PHP with a tag, here is the code: echo '<a class="ui label" onclick="variant_desc('.$product_id.');"> '.$variant->Field1.' </a>'; When I click the function mentioned in the tag, I get the ...

Prisma DB is a versatile database that excels in handling m-n

In my database, I have implemented a structure with 3 tables: Member, Characters, and MemberCharacters. Each member can have multiple Characters, and each Character can be used by multiple Members. To handle this many-to-many relationship, I have utilized ...

"Combining jQuery and JavaScript to handle form submissions in un

What happens when you combine the Javascript onSubmit handler and jQuery submit handler? <form action="" method="post" onSubmit="myJavascriptHandler();"> <input type="submit" /> </form> <script type="text/javascript"> $("form") ...

Customize CSS based on user's device in Google Script Web App

Seeking Clarity: I have a straightforward project involving a Google Script / Web App, but I am struggling to find a way to load a specific CSS file based on the user's device. In other words, rather than focusing on responsive design, I need to loa ...

In Angular 16, allow only the row that corresponds to the clicked EDIT button to remain enabled, while disabling

Exploring Angular and seeking guidance on a specific task. I currently have a table structured like this: https://i.stack.imgur.com/0u5GX.png This code is used to populate the table: <tbody> <tr *ngFor="let cus of customers;" [ngClass ...

Shooting star css animation featuring pre and post effects

Trying to create a falling star using CSS animation. I made a star with a pseudo element, but I'm having trouble setting the animation in the pseudo-element. i{ position: relative; width: 0; height: 0; border-left: 12px solid transpa ...

Issue with Datatable when making an ajax request

My web application utilizes Datatable and AJAX to retrieve data. Below is a snippet of my code: <script> $(document).ready(function() { $('#mytable').DataTable(); } ); </script> <body> <h2>AJAX SELECT&l ...

How can we rearrange the positions of three items in an array?

I am dealing with a function that returns an array of objects structured like this const allGreen = _.filter( sidebarLinks, side => !isServicePage(side.slug.current) ); https://i.stack.imgur.com/dR8FL.png I am attempting to rearrange the positions of ...

Error encountered while attempting to install ungit on Windows XP: Unable to locate file directory in C:/Documents

Ungit seems like the ideal tool to gain a better understanding of git, thanks to its graphical interface that simplifies the process. I came across this video explanation which is very helpful in grasping how git functions, even if you don't intend to ...

`What is the best way to extract elements from a table once all components have been fully rendered using React and testing-library/react?`

Attempting to properly test my UsersTable page in React has presented a challenge, as the testing library seems to access the elements before they have had a chance to render. Please review the code snippet below: UsersTable.js import React, { useState, u ...

Combining one item from an Array Class into a new array using Typescript

I have an array class called DocumentItemSelection with the syntax: new Array<DocumentItemSelection>. My goal is to extract only the documentNumber class member and store it in another Array<string>, while keeping the same order intact. Is th ...

Unable to import the Node.js array in the import() file

I have encountered an issue while building an array path for the Router.group function. The parameter passed to Router.group is added to the end of the this.groupPath array, but when I check the array data within an import(), it appears to be empty. What c ...

Creating an HTML form in Django using forms.py

I created a Django web application that includes an authentication system. Within this system, I have a user registration view, a customer model, and a UserCreationForm in forms.py: class CustomerSignUpForm(UserCreationForm): first_name = forms.CharFie ...

What could be causing this code to only modify one element instead of both?

One input field should be able to change two elements, however with jQuery it appears that only one element is being modified. When rearranging the order of elements in the function, such as having #inCoin first and then #receive_amount, only the #inCoin ...

What is the best way to style a tooltip in an ASP.NET application using CSS?

protected void grd_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { foreach (TableCell cell in e.Row.Cells) { ...

Is it possible to apply fog to a specific area in Three.js instead of being dependent on the distance from

Picture this: a vast THREE.PlaneGeometry representing the floor with a camera placed at an arbitrary spot within the scene. By manually adjusting the near and far values of the fog, I can effectively conceal the outer edges of the plane to create the illu ...

Attempting to implement age validation in an ASP.NET web application by using the selected value from a dropdown list and a date picker

I am currently developing a booking web application for a hotel. The form includes fields where the user must enter their own information and information for others. I would like to implement age validation and create dependency between two fields. The fir ...

A function that receives another function as a parameter

I need assistance in defining a function that can call another function passed as a parameter within the main function. function displayMessage(title, message, button, callback) { console.log(title, message, button); if (typeof(callback) !== "f ...