Issue
I'm trying to implement an infinite slider which should loop forever with no need for buttons to move to the next or the previous, instead, the user can move or pause the slider using touch (this part is not implemented yet, so it's not in the code snippet)
the problem is that I can't get my hands on the logic of the infinite slider, it starts with the last slide (in my case it has the number 5) then gos to 2 => 3 => 4 => 5 => 1 then stops. also, I don't know why it ignores the condition which checks currentSlide
's value
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 find the full code here : https://codepen.io/Marya-ai/pen/ZEwRNRE
I would highly appreciate your help and suggestions.
Solution
If you will look into the console, then you will see that you have error(cannot read properties of undefined). So to fix this you should make
if(currentSlide === 0 || currentSlide === numOfSlides-1) setToInitialPosition();
to avoid length of array + 1
issue
But if you will make console log of your data (currentSlide) you can notice that your representation(numbers) doesn't satisfy data. To avoid confusion make your code reliable on data
Answered By - mxxnseat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.