How to create a continuous loop for a JavaScript carousel

I have a simple carousel set up with this code. I'm looking to make it loop back to the beginning after reaching the third quote-item.

Can anyone provide some guidance? Thank you!

This is the JavaScript used:

    <script>
show()
     $(function() {
    var currentCarousel = 0;
    function changeCarousel() {
      $('.quote-item').hide();
      $('.quote-item:eq('+ currentCarousel +')').show();
      currentCarousel = currentCarousel + 1;
      setTimeout(function(){ changeCarousel(); }, 8000);
    }
    changeCarousel();
    $('.quote-change').click(function(e) {
    e.preventDefault();
      changeCarousel();
    });
      });
    </script>

And here is the HTML structure:

 <div class="quote" >
  <div class="quote-item">
    <div class="quote-image">
      <img src="" alt="quote 1">
    </div>                                    
    <div class="quote-text">
        quote text one
    </div>
  </div>
    <div class="quote-item">
    <div class="quote-image">
      <img src="" alt="quote 2">
    </div>                                    
    <div class="quote-text">
        quote text Two...
    </div>                                 
  </div>
    <div class="quote-item">
    <div class="quote-image">
      <img src="" alt="quote 3">
    </div>                                    
    <div class="quote-text">
        quote text THREE...
    </div>                                 
  </div>
<a href="#" class="quote-change">next</a>
</div>

Answer №1

Give this a try:

$(function () {
    var currentCarousel = 0;
    var timeoutID = null;
    var timeoutDuration = 2000;
    var quoteChange = $('.quote-change');
    var quoteItems = $('.quote-item');
    var numQuotes = quoteItems.length;
    
    function changeCarousel() {
        quoteItems.hide();
        quoteItems.eq(currentCarousel).show();
        currentCarousel += 1;
        if (currentCarousel === numQuotes) { currentCarousel = 0; }
        clearTimeout(timeoutID);
        timeoutID = setTimeout(function () {
            changeCarousel();
        }, timeoutDuration);
    }
    changeCarousel();
    quoteChange.click(function (e) {
        e.preventDefault();
        changeCarousel();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="quote">
    <div class="quote-item">
        <div class="quote-image">
            <img src="" alt="quote 1" />
        </div>
        <div class="quote-text">quote text one</div>
    </div>
    <div class="quote-item">
        <div class="quote-image">
            <img src="" alt="quote 2" />
        </div>
        <div class="quote-text">quote text Two...</div>
    </div>
    <div class="quote-item">
        <div class="quote-image">
            <img src="" alt="quote 3" />
        </div>
        <div class="quote-text">quote text THREE...</div>
    </div>
<a href="#" class="quote-change">next</a>

</div>

Additionally, you need to include a clearTimeout(); since the click handler calls the changeCarousel() function as well, creating a conflict.

Imagine that by default, your setTimeout keeps calling changeCarousel() recursively. If you decide to click on the "next" button in the middle of the loop, the new carousel item will only stay visible for the remaining time instead of the full duration. This can cause an inconsistency in the display timing.

I hope you find this information helpful.

Answer №2

Make sure to update your changeCarousel function so that when the currentCarousel is greater than or equal to the number of slides, it resets back to 0.


function changeCarousel() {
    $('.quote-item').hide();
    $('.quote-item:eq('+ currentCarousel +')').show();          
    if(currentCarousel >= slides.length) {
        currentCarousel = 0;
    } else {
        currentCarousel++;
    }
    setTimeout(function(){ changeCarousel(); }, 8000);
}

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

Discover the power of the "Load More" feature with Ajax Button on

After browsing through the previous questions and experimenting with various techniques, I've come close to a solution but still can't get it to work. The closest example I found is on Stack Overflow: How to implement pagination on a custom WP_Qu ...

Activate/Deactivate toggle using Vue.js

new Vue({ el: '#app', data: { terms: false, fullname: false, mobile: false, area: false, city: false, }, computed: { isDisabled: function(){ return !this.terms && !this.fullname && !this.mob ...

What steps can I take to make sure that a sub component's props are refreshed properly?

I'm encountering an issue with RTK queries in my project. I have a parent component that contains a table component. When a refresh event occurs, such as deleting data, the parent component receives updated data and passes it down to the child compone ...

Tips for properly implementing ng-hide and ng-show across various sections of your single page application

Currently working on a Single Page Application (SPA). I've included some buttons in the side navigation with the intention of displaying different content when they are clicked. However, I encountered an issue where using ng-hide and show didn't ...

Utilizing JQuery AJAX and PHP for Data Encoding

My webpage is encoded in HTML with the charset ISO-8859-2. All content on the page adheres to this charset and appears correctly. However, I am facing an issue when making an Ajax call to a PHP server. When I send the character á and receive the same valu ...

Guide to building a nested React component

My custom dropdown component requires 2 props: trigger (to activate the dropdown) list (content to display in the dropdown) Below is the implementation of my component: import { useLayer } from "react-laag"; import { ReactElement, useState } fr ...

Automatically scraping Facebook API data with PHP

I'm completely new to php and I am looking for a way to automatically scrape metadata. I came across a solution, but I am unsure how to implement it in php. POST /?id={object-instance-id or object-url}&scrape=true Can anyone provide a sample php ...

What is the process of integrating data retrieved from an SQL query into a Pug template using Express and MySQL?

Currently, I am in the process of developing a basic web application that will initially show a list of bus route numbers and names upon landing on the page. My tech stack includes MySQL integrated with Express and Pug. Below is the server-side code snippe ...

Make sure to wait for the VueX value to be fully loaded before loading the component

Whenever a user attempts to directly navigate and load a component URL, a HTTP call is initiated within my Vuex actions. This call will set a value in the state once it has been resolved. I am looking to prevent my component from loading until the HTTP ca ...

Angular JS may encounter a cross domain problem when attempting to post on a third-party website

HTML Code: <div ng-app="myApp" ng-controller="myController"> <div> <input type="button" data-ng-click="submit()" ...

`CSS Content Placeholder Issue When Used Alongside JavaScript`

Let me explain a bit, I have a master page named UserProfile.master which has a content placeholder linked to UserProfileWall.aspx. Now, I am trying to incorporate some additional JavaScript and a second CSS file in the userprofilewall page. However, whene ...

Aligning container divs at the center in various screen resolutions

I recently constructed a portfolio website using Bootstrap and Isotope JS. In my layout, I have a container div which works perfectly when viewed on a desktop browser - displaying 3 divs in one line. However, the issue arises when the resolution changes an ...

The BBCode seems to be malfunctioning

I created a custom BBCode for my PHP website to display tabbed content on a page. After testing the BBCode on a separate webpage and confirming there are no errors, I am facing an issue where the tabbed content is not showing up on the actual posting page. ...

Occupying both horizontal and vertical space in a Bootstrap column

I have set up my buttons like this: https://i.stack.imgur.com/OMfhp.png In the image, you can see that the Left Option Button is larger, and I want all buttons to be like that. They are supposed to be aligned next to each other as I am using the Bootstra ...

In JavaScript, unchecking a radio button results in all options becoming uncheckable

I have a pure CSS accordion and I want to enhance it with some JavaScript functionality for users who have JavaScript enabled. The CSS accordion currently utilizes the :checked pseudo-class. The new feature I am looking to add is: if a button that is alre ...

A guide on utilizing the React Suite range slider in rsuite

Hello there, I recently started working with the UI framework rsuite (React suite) and everything was going smoothly until I tried to use the Range slider component's API. Unfortunately, I am facing some issues with the labels and tooltips not display ...

Guide on implementing factory updates to the display

I am attempting to update a reference within my factory in an asynchronous fashion, but I am not seeing the changes reflected in my view. View <div ng-repeat="Message in Current.Messages">{{Message.text}}</div> Controller angular.module(&ap ...

Error in Next.js: .env variable not defined

I recently transitioned my project from React to Next.js and encountered an issue where my environment variables are showing as undefined, even though they were functioning correctly in React. Can someone provide some guidance or assistance with this probl ...

Analyzing HTML markup to locate an anchor tag

While attempting to parse an HTML code using BeautifulSoup in order to retrieve a link that is hidden and does not appear on the website, I have encountered difficulties as it only retrieves links visible on the page. Is there a method to effectively par ...

Implementing a search filter for special characters in AngularJS

Looking to filter an array of players by their names, but facing a challenge with special characters in the names. Found a code snippet on Google that looks like this: $scope.modelFilterNormalized = function(){ if($scope.modelFilter) return $sco ...