The slider components have an endless loop feature that only runs once before coming to a

I'm working on creating an infinite slider that loops continuously without the need for navigation buttons. Instead, I plan to allow users to control the slider using touch gestures (although this functionality is not yet implemented in the code snippet).

However, I've encountered a problem with the logic of the infinite slider. It seems to start at the last slide (numbered 5 in my case), then goes to slides 2, 3, 4, 5, and finally 1 before stopping. Additionally, I can't figure out why it's disregarding the condition checking the value of currentSlide.

const allSlides = document.querySelectorAll(".testimonials-tp__review-slider__slide");
const numOfSlides = allSlides.length ;

let currentSlide = 0;

const slider = () => {

    // Setting each slide's initial position:
    // setToInitialPosition();

     // Moving to the next slide after 2s:
    setInterval(sliding, 2000);
}

const sliding = () => {
    // Reset to the first slide for an infinite loop:
    if(currentSlide === 0 || currentSlide === numOfSlides) setToInitialPosition();
    
    // Making the current slide outside the container:
    allSlides[currentSlide].style.transform = `translateX(${(currentSlide) * -100}%)`; 
    
     // Bring the next slide to the container:
     allSlides[currentSlide + 1].style.transform = `translateX(0%)`;
     ++currentSlide;
}

const setToInitialPosition = () => {
    allSlides.forEach((slide, index) => {
        // Reset all slides to their initial positions:
        slide.style.transform = `translateX(${index * 100}%)`;
    });

    // Reset the current slide index:
    currentSlide = 0;
};

slider();

You can access the complete code here: https://codepen.io/Marya-ai/pen/ZEwRNRE

Your help and suggestions would be greatly appreciated.

Answer №1

Upon inspection of the console, you may notice an error stating "cannot read properties of undefined." To resolve this issue, ensure that your code includes the following:

if(currentSlide === 0 || currentSlide === numOfSlides-1) setToInitialPosition();

This adjustment will help prevent any issues related to the length of the array.

If you further examine the data through a console log of the currentSlide variable, you may observe inconsistencies between the numbers represented and the actual data. It is recommended to align your code with reliable data to avoid confusion.

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

Tips for submitting a form using alternative methods of action

Currently, I am facing a challenge in retrieving information from a database using submit buttons with the same name. I assign a value to these buttons, which corresponds to the id of the row, enabling me to perform different actions. However, I am unsure ...

The loading time for the Docker index HTML file page is unacceptably slow

Sample Dockerfile: FROM ubuntu:22.04 RUN apt-get update RUN apt-get install -y nginx COPY -r dist/ /var/www/html/ CMD service nginx start && tail -F /var/log/nginx/error.log After that, run the following commands: docker build -t website . docker ...

Unlocking the Secrets: Expert Methods to Obtain Assets through HttpClient in Angular

After researching similar inquiries, such as the response provided in this thread, it seems that downloading or reading files from the assets directory can be accomplished easily by utilizing the get method of the HttpClient. For instance, if I have a Down ...

Top method for identifying browser window modifications such as navigating back, altering the URL, refreshing, or closing the window

Currently, I am developing a testing application that requires me to trigger a finsihTheTest() function in specific situations. These situations include: When the user attempts to reload the page. When the user tries to navigate back from the page. If the ...

What is the reason behind the for of loop breaking within an async function instead of properly awaiting the execution?

Update 2: I made changes to use setTimeOut instead, which fixed the issue. Check out the accepted answer for details on what was causing the error. The code below is now functioning properly. async function getSlices() { const imgBuffs = await sliceImg ...

"Keeping your HTML content up-to-date with AngularJS dynamic updates

I've noticed that when I upload changes to my AngularJS HTML partial files, there is a caching issue where the old data is displayed. It takes a few refresh actions before the changes become visible. Is there a way to make these changes appear immedi ...

Successful execution occurring prior to beforeSend in a Cordova iOS application utilizing jQuery Ajax

After making some changes to the HTML of the login button, I encountered an issue where the alert was being triggered before the button's HTML had updated when testing on my iPhone using a Cordova-built app. Strangely, this problem did not occur when ...

Exploring the world of jQuery waypoints and the art of modifying

This is only the second question I'm asking here, so please be gentle! I've been experimenting with jQuery waypoints to dynamically show and hide a border under my navigation menu based on scroll position. For instance, when the sticky nav is ov ...

Creating a Dojo HTML template involves incorporating repetitive sections of HTML code within the template structure

I am working with a custom Dojo widget that is based on a template and has an HTML template stored in a separate .html file. Here is the Dojo Widget code snippet: define("dojow/SomeWidgetName",[ "dojo/_base/declare", "dijit/_WidgetBase", "dijit/_Templat ...

Failure to receive Ajax XML data in success callback

I am struggling to access the book.xml file that is located in the same folder as other files. Everything seems fine, but the ajax function refuses to enter the success state and instead shows an [object object] error message. The XML file is very simple, ...

The data visualization tool Highchart is struggling to load

As I try to integrate highcharts into my website, I encounter an unexpected error stating TypeError: $(...).highcharts is not a function. Below is the code snippet in question: @scripts = {<script src="@routes.Assets.at("javascripts/tracknplan.js")" ty ...

Utilizing Vue.js i18n for a multi-line text display

Currently, I am implementing i18n single file component in order to provide translation support for my application. In order to achieve this, I have been utilizing the i18n tag as shown below: <i18n> { "fr": { "text": "Lore ...

Best practices for using parent and child methods in Vue applications

I'm exploring the most effective approach to creating a modal component that incorporates hide and show methods accessible from both the parent and the component itself. One option is to store the status on the child. Utilize ref on the child compo ...

What is the best way to handle constants in TypeScript?

I am facing an issue with a React component I have created: const myComponent = ({constant}: Iprops) => ( <div> {CONSTANTS[constant].property ? <showThis /> : null </div> ) The error message says 'element implicitly has ...

socket.io / settings when establishing a connection

I'm facing an issue in my node.js / Express.js app where I need to pass parameters with the socket.io connection (saw a solution in another post). On the client side, here is a snippet of my code: edit var socket = io.connect('/image/change&ap ...

Adding an event listener to detect left or right mouse clicks - using onclick doesn't capture right clicks

I'm currently in the process of applying for an Internship through this Internship Link One thing that caught my attention right away is the issue with uploading or pasting a cover letter. When attempting to upload or paste a cover letter, it redirec ...

Inheritance best practices for node.js applications

In C#, the concept of inheritance can be easily demonstrated through classes like Animal and Dog. class Animal { string name; public Animal() { } } class Dog : Animal { public Dog() : base() { this.name = "Dog"; } } When working ...

How can I trigger a CSS animation to replay each time a button is clicked, without relying on a timeout function?

I am having trouble getting a button to trigger an animation. Currently, the animation only plays once when the page is refreshed and doesn't repeat on subsequent clicks of the button. function initiateAnimation(el){ document.getElementById("anima ...

Creating an HTML document with unique characters

I am currently facing an issue with writing special characters in HTML. My program is designed to edit an HTML file and allow users to replace content using a text box. However, I am struggling to add characters like "ç", "á", "ö", etc. These character ...

The value property of the input element is returning as undefined

The input value entered is always returning undefined. Despite trying various solutions found in similar questions, my jQuery code continues to return undefined. jQuery: $( document ).ready(function() { $('#Input').keypress( function(e ...