I am currently new to Javascript and I am stuck on this problem. The goal of this code is to cycle through 3 different combinations of separate text(slide) and images(slideimg) upon pressing the previous and next buttons. Currently my code works perfectly when going from element 0 to 2 in the array, both up and down, but I need the array to reset back to [0] while the [2] element is active and the next button is pressed, while also giving the active class to [0] and removing the active class from [2]. I also need the array to do the opposite when the previous button is pressed while [0] is active. I have tried a few variations of solutions, but no luck with displaying the content properly 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);
Remove the active
from the current slide initially. Then change currentSlide
by adding 1 and using modulo:
const nextSlide = function () {
slides[currentSlide].classList.remove('active');
imgs[currentSlide].classList.remove('active');
currentSlide = (currentSlide + 1) % 3;
slides[currentSlide].classList.add('active');
imgs[currentSlide].classList.add('active');
};
Do the same for prevSlide
, except change the currentSlide
assignment to:
currentSlide = (currentSlide + 2) % 3;
(The + 2
carries out the same sort of logic as - 1
, except that it will land on the correct number when the slide starts at 0. Modulo won't work as desired on a negative number; -1 % 2
gives you -1
, not 2
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.