The updated Bootstrap 4 carousel is only working halfway as expected when attempting to double it up, causing the scroll loop to stop functioning

Discovering a fantastic carousel modification was an exciting find, which can be accessed Here. However, when attempting to place two carousels on one page, issues arose with the scrolling functionality. While I managed to make them operate on the correct Carousel, they failed to loop properly once reaching the end. Instead of smoothly cycling from 1 to 8 and back to 1, they would loop to an empty state then repopulate all slides. The goal is to resolve this seamless looping behavior.

If you want to see how a single item functioned correctly and aim to achieve the same for the double carousel setup, please refer to this link.

Please note that the malfunction only occurs when not in the single-item view (mobile view). The objective is to fix its operation when displaying three items at col-md size. To better understand the issue when running the code, ensure testing in full-screen mode to observe the problem accurately.

Answer №1

If you wish for your code to function across multiple carousel instances on the same page, you'll need to target only the specific instance of the carousel. To achieve this, store the current carousel in a variable (denoted as $c in the example provided below):

$c = $e.closest('.carousel-inner'),

Then, utilize this variable to restrict the jQuery selectors to the current carousel alone by replacing $(selector) with $(selector, $c):

// JavaScript Document

$('#carouselExample').on('slide.bs.carousel', modCarousel);
$('#test').on('slide.bs.carousel', modCarousel);

function modCarousel (e) {

    var $e = $(e.relatedTarget),
        idx = $e.index(),
        itemsPerSlide = 3,
        $c = $e.closest('.carousel-inner'),
        totalItems = $('.carousel-item', $c).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', $c).eq(i).appendTo($c);
            }
            else {
                $('.carousel-item', $c).eq(0).appendTo($c);
            }
        }
    }
};
@media (min-width: 768px) {
  /* show 3 items */
  .carousel-inner .active,
  .carousel-inner .active+.carousel-item,
  .carousel-inner .active+.carousel-item+.carousel-item {
    display: block;
  }
  ...

}
<!DOCTYPE html>
<html lang="en">

<head>
  ...
</head>

<body>

  <div class="container">
    <div id="carouselExample" class="carousel slide" data-ride="carousel" data-interval="1850">
      ...
    </div>

    <div id="test" class="carousel slide" data-ride="carousel" data-interval="2100">
      ...
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  ...
</body>

</html>

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

How can we minimize the data contained in JSON HTML markup?

https://i.stack.imgur.com/mzuB0.png Currently, I am attempting to find a way to conceal the last 12 digits in the price shown on a button, as it is excessively long. The method I am utilizing involves a JSON api and insertAdjacentHTML markup. This snipp ...

Facing challenges in both client-side and server-side components

import axios from 'axios'; import Image from 'next/image'; export const fetchMetadata = async({params}) => { try { const result = await axios(api url); return { title: title, description: Description, } / } catch (error) { con ...

Establishing a PHP session variable and then initiating a redirect to a new page through the HREF method

I am working on a table that pulls IDs from a MySQL table named auctiontable and displays them in rows. Currently, I can easily append ?aid="1"or ?aid="2" to the end of the href attribute to utilize $_GET. However, I want to prevent users from controllin ...

Whenever I am building a React application, I encounter a bug that states: "node:fs:1380 const result = binding.mkdir()"

Whenever I try to enter the command: create-react-app my-app --template typescript I keep encountering this error message: node:fs:1380 const result = binding.mkdir( ^ Error: EPERM: operation not permitted, mkdir 'D:\ ...

Update a variable in one component class using another component

My Hue class in a component contains a variable that I'm trying to modify: export default class Hue extends Component { state = { toggleState : false, toggleWhite : false } render(){...} ... } Within this component, I can chang ...

Having trouble retrieving the necessary redirect_uri in react-facebook-login

I am currently working on implementing Facebook OAuth in my express/NodeJS app using the authorization code flow. To fetch the authorization code, I am utilizing the react-facebook-login node module. While I can successfully obtain the authorization code i ...

Original: full size responsive background images without stretchRewritten: high-quality

I have incorporated the Full page scroll feature for a website from GitHub user peachananr. You can find it here: https://github.com/peachananr/onepage-scroll My goal is to assign a resizable background image to each "page". I am using the CSS rule ' ...

Tips for keeping your avatar contained within a Bootstrap grid

I am attempting to adjust the positioning of my "image holder" (avatar) with a top and bottom margin of 3px, but when I implement this change, the image holder shifts outside of the grid. Below is the code snippet in question: <div class="container con ...

Interactive canvas artwork featuring particles

Just came across this interesting demo at . Any ideas on how to draw PNG images on a canvas along with other objects? I know it's not a pressing issue, but I'm curious to learn more. ...

Tips for altering the label color of an md-input-container after text has been entered

Is there a way to dynamically change the color of an md-input-container label after certain input is added? The default grey color gives the impression that the field is disabled. I specifically want to modify the color of the label "Description" when the ...

Encountering "Index not defined" error while attempting to insert data into the

Warning: Undefined index: postId in C:\xampp\htdocs\ajax-complete\save_post.php on line 4 Warning: Undefined index: postTitle in C:\xampp\htdocs\ajax-complete\save_post.php on line 8 Warning: Undefined index: p ...

Can a dynamic react component be inserted into a standalone HTML document without the need for file downloads or server support?

I am implementing React for a Single Page Application (SPA) project where users can customize a component's font size, color, etc., and then embed this customized component into their website. I'm looking for a way to bundle the component and pre ...

A guide to retrieving hyperlinks from an HTML table with Selenium

I am currently working on a Java and Selenium code snippet like the one below: public static void main(String[] args){ WebDriver driver; DesiredCapabilities caps; caps = new DesiredCapabilities(); caps.setCapability(PhantomJSDriverService ...

Error message triggered by Yubikey in WebAuthn Authentication API

Having trouble with implementing WebAuthn support on a new website, specifically encountering issues during the navigator.credentials.get() call. The client browser being used is Firefox 85.0 on Fedora 33, and the server is Apache httpd also on Fedora 33. ...

Sending KeyValuePair or IDictionary as payload to Web Api Controller using JavaScript

In my web api controller, I am trying to post two parameters: a flat int ID and an IDictionary (or similar equivalent). [HttpPost] public void DoStuff(int id, [FromBody]IDictionary<int, int> things) { } var things = new Array(); things.push({ 1: 10 ...

Does the Android 4.3 Internet browser not support @font-face declarations?

After my Samsung Galaxy S3 phone recently updated from Android 4.1.3 to Android 4.3, I noticed that some of the websites I designed are not displaying the fonts correctly. These sites were tested on the Android internet browser and use @font-face. How can ...

Best practice for sending an email including both the sender's name and email address in the FROM

I'm having difficulty with getting this to function the way I want. I want the email to be sent to me in the following format: Person's Name <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="becedbcccdd1d0cdf0dfd3d ...

A guide on triggering a function when the context changes in a React application

Can I automatically trigger a function in a component whenever the context changes? Specifically, I have a variable named isLoggedIn in the Navbar module. Whenever a user logs in, the value of isLoggedIn is updated to true. In my Blog module, how can I m ...

The error message "ReferenceError: $ is not defined" is displayed within

My current requirement involves loading templates within an iframe, and to achieve this, I have implemented the following code: <div class="col m8 l8 s12 margin-top-30" id="hue-demo-bg-div"> <iframe id="myiframe" src="/themes/{{$themeid}}.ht ...

Issue with setInterval function execution within an Angular for loop

My goal is to dynamically invoke an API at specific intervals. However, when attempting to utilize the following code snippet in Angular 7, I encountered issues with the interval timing. I am seeking a solution for achieving dynamic short polling. ngOnIn ...