Tips for postponing the initiation of multiple carousels on a single page?

On my webpage, there are several bootstrap 5.3 carousels that I want to start with a delay. The plan is for each carousel to begin at different intervals – the first one after 1 second, the second after 2 seconds, the third after 3 seconds, and so forth.

Every carousel is uniquely identified with an id, for example:

<div class="card-image">
    <div id="carousel__<?php echo $row['guid']; ?>" class="carousel slide carousel-fade" data-ride="carousel">
        <div class="carousel-inner">
            <div class="carousel-item active">
                <a href="<?php echo $galleryLink; ?>">
                    <img class="img-card-gallery" src="<?php print $coverPhoto . '?t=' . time(); ?>" alt="">
                </a>
            </div>
            <?php
for ($i = 0; $i < count($imgfileNames); $i++) {
    echo ' 
        <div class="carousel-item">
            <a href="' . $galleryLink . '">
                <img class="img-card-gallery" src="' . $imgfileNames[$i] . '?t=' . time() . '" alt="' . $imgartTitles[$i] . '">
            </a>
            <div class="carousel-caption d-none d-md-block">
            <!-- Here you can add Caption -->
            </div>
        </div>
        ';
}
            ?>
        </div>
    </div>
    <!-- <a href="<?php echo $galleryLink; ?>"><span class="<?php if($galleryTitle=='') echo 'card-title-without-text'; else echo 'card-title-with-text'; ?>"><?php echo $galleryTitle ?></span></a>-->
</div>

Unfortunately, my JavaScript code is not functioning as expected, as all the carousels start simultaneously. Here is the problematic snippet:

<script>
    $(document).ready(function() {
        var carousels = $('.carousel-fade');
        var initialInterval = 1000; 

        carousels.each(function(index, carousel) {
            var carouselInstance = new bootstrap.Carousel(carousel, { interval: 0 }); 
            console.log('Setting the carousel number ' + index + ' with an interval of ' + initialInterval + 'ms');
            setTimeout(function() {
                carouselInstance.interval = initialInterval; 
                carouselInstance.cycle(); 
            }, 1000); 
            initialInterval += 1000; 
        });
    });
</script>

Answer №1

Here are the modifications made to your code:

 <script>
    $(document).ready(function() {
        var carousels = $('.carousel-fade');
        var initialInterval = 1000;

        carousels.each(function(index, carousel) {
            var carouselInstance = new bootstrap.Carousel(carousel, { interval: 0 });
            console.log('Carousel number ' + index + ' set up with an interval of ' + initialInterval + 'ms');
            setTimeout(function() {
                carouselInstance.interval  = initialInterval; // Change the interval using carouselInstance.interval
                carouselInstance.cycle();
            }, initialInterval); // Ensure the delay for each carousel is set to initialInterval
            initialInterval += 1000;
        });
    });
</script>

Modify the carousel's interval using carouselInstance.interval, as it controls the timing internally.

Adjust the setTimeout delay to initialInterval milliseconds for the desired start delay of each carousel.

We hope this resolves your issue. Thank you for your patience.

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

Checkbox Hierarchy: Children marked as either Checked or Unchecked based on parent selection

Hello, I have a form that contains nested checkboxes on three levels. Using jQuery, I am trying to check/uncheck all the children when I check a parent level... and if any of the children are unchecked, uncheck the parent as well. I have attempted this m ...

Change a space-separated string containing coordinates into an array of JavaScript objects

Here is a string separated by spaces: const coordinates = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604" Now, we want to convert it into an array of objects: const coordinatesArray = [ { lat: 42.44492, lng: 75.637764 }, { lat: 42.4455 ...

Retrieve the content from paginated pages using ajax, apply a filter to it, and then add it to the existing page

My blog needs more functionality and I want to avoid using paginated pages. My idea was to extract content from these paginated pages through ajax, filter it, and add it to a specific div element. I'm not completely confident if I am on the right tra ...

Webshot is unable to retain any images

I attempted to utilize the Node package Webshot. The function is being executed, "OK" is printed to the console, but no files are saved to the specified folder. What could I be overlooking? if (Meteor.isServer) { var webshot = Meteor.npmRequire(&apos ...

Detecting when the Ctrl key is pressed while the mouse is hovering over an element in React

In my project, I have implemented a simple Grid that allows users to drag and drop items. The functionality I am trying to achieve is detecting when the mouse is positioned on the draggable icon and the user presses the Ctrl key. When this happens, I want ...

differences in opinion between JavaScript code and browser add-ons/extensions

As the owner and developer of an e-commerce website, I find that potential customers often contact us regarding ordering issues. Upon investigation, we consistently discover that the problem is caused by JavaScript errors. We frequently check their browse ...

Experiencing issues with obtaining req.params.id undefined while initiating a put request

Encountering an issue while making a PUT request using Postman, as an error occurs in the VSCode terminal with the message: let product = await Product.findById(req.params.id); ^ TypeError: Cannot read property 'id' of undefined. The request ...

How to send a DOM element's value to an AJAX request using HTML.PagedList parameters

As I delve into learning ajax requests, I find myself questioning if I am on the right track. Currently, I have a page that incorporates pagination, sorting, and searching functionalities. My goal is to implement these features using ajax to avoid reloadin ...

Issue with running the Jquery each function within a textbox inside an ASP.NET gridview

Below is the gridview markup: <asp:GridView ID="gvDoctorVisits" runat="server" DataKeyNames="AdmissionId" class="tableStyle" AutoGenerateColumns="False" Width="100%" EmptyDataText=& ...

"The authentication cookie fields are not defined when trying to get the authentication in the Express framework

After setting up my React client on port 3000 and Express on port 5000, I encountered an issue. When logging in, the cookie fields are set without any problems. However, when trying to retrieve the isauth value, it shows as undefined. //login log message ...

What is the best way to effectively adjust the code structure in a Node.JS project?

[Summarized] Focus on the bold parts. Although I am relatively new to Node.JS, I have been able to successfully build some projects. However, I have come across a burning question that has left me frustrated after searching Google for answers without much ...

Printing keys of objects in an array in AngularJS through iteration

Here is an array of objects that I am attempting to iterate in ng-repeat and print keys, but I am facing some challenges. $scope.directivesInfo = [ {"ngRepeat": {"enter": true, "leave": true, "move": true, "add": false, "remove": false}}, {"ngView ...

Issues with Google Fonts failing to load correctly

Would you mind taking a look at this issue for me? In all browsers except Firefox, the expected behavior is that a web font remains invisible until fully loaded, preserving space on the page. Interestingly, in Chrome and IE9 (the browsers I tested), ther ...

Form data triggering inaccurate results in ajax response

After following online tutorials and seeking help from Stack Overflow, I am still struggling with a strange issue related to AJAX. I appreciate any assistance in solving this problem. I am trying to create a feature where users can search for match result ...

Failure to append an object to the array occurs when submitting an HTML form

I am facing an issue with a form that is supposed to add input values to an array as objects when submitted. However, every time I submit the form, the console briefly shows that there is an array with one object, only for it to disappear. Below is the f ...

What is the reason behind only the final input value being shown on the screen?

I'm encountering an issue with my input fields. I have a total of five input fields. After filling all of them and clicking the button to display them on the screen, only the last one I entered is shown in all places... (let me know if this explanatio ...

Node.js with Socket.io causes multiple events to be triggered

Currently, I am in the process of developing a rochambo game using node.js and socket.io. The game works as follows: A player places a bet, which is then sent to all other players. These players can choose a sign and click on 'challenge'. Howeve ...

JavaScript: exporting everything from ... causing excessive bloat in the build file

After building my react-app with create-react-app, I noticed a decline in performance. Here is the structure of my project: /store actions.ts reducers.ts /module1 module1.actions.ts module1.reducers.ts /moduleN moduleN.actions.ts m ...

Is your href in javascript not functioning properly?

Recently, I completed the development of a mobile web application. Overall, everything seems to be working smoothly except for one issue: there is a link with JavaScript in its href that is causing problems. Strangely enough, this link works perfectly fi ...

Troubleshooting the Create Order Issue: Integrating PayPal Checkout with Smart Payment Buttons using React and Redux

Every time I attempt to process a payment, I encounter a 422 error: Unprocessable entity. The issue arises when I try to dynamically capture the purchased item details received from the redux store. I tried following this example (duplicate): PayPal Check ...