As a newcomer to Javascript, I am facing a challenge with this particular issue. The objective of this script is to rotate through 3 different combinations of text (slide) and images (slideimg) when the previous and next buttons are clicked. Currently, my code works flawlessly when transitioning from element 0 to 2 within the array, in both directions. However, I am struggling with resetting the array back to [0] while the [2] element is active upon clicking the next button. Additionally, I need to assign the active class to [0] and remove it from [2]. Similarly, when the previous button is clicked while [0] is active, I want the array to adjust accordingly. I have experimented with various solutions but haven't been successful in properly displaying the content so far.
const slides = document.querySelectorAll(".slide");
const imgs = document.querySelectorAll(".slideimg");
const prevButton = document.getElementById("larrow");
const nextButton = document.getElementById("rarrow");
var currentSlide = 0;
slides[currentSlide].classList.add("active");
imgs[currentSlide].classList.add("active");
var nextSlide = function(){
if(currentSlide < 2) {
currentSlide+=1;
}
slides[currentSlide - 1].classList.remove("active");
slides[currentSlide].classList.add("active");
imgs[currentSlide - 1].classList.remove("active");
imgs[currentSlide].classList.add("active");
};
var prevSlide = function(){
if(currentSlide > 0){
currentSlide--;
}
slides[currentSlide].classList.add("active");
slides[currentSlide + 1].classList.remove("active");
imgs[currentSlide].classList.add("active");
imgs[currentSlide + 1].classList.remove("active");
};
nextButton.addEventListener("click", nextSlide);
prevButton.addEventListener("click", prevSlide);