I’m having an issue with a carousel. Let me explain.
When i click on any of the photos, it opens a modal/carousel which is working as planned. But once i close this said modal and try to click on any other photo, when clicking on the next button, it’s not doing +1, but +2 and increasing each time i close the modal.
Any solution ? Code below (i tried to comment it as much as possible to make it being understandable.
let currentState = 0
//Display photo/video inside modal + carousel
function displayPhoto() {
const photos = document.querySelectorAll(".photo")
const prevButton = document.querySelector(".prev-button");
const nextButton = document.querySelector(".next-button");
console.log(photos)
for(let i = 0; i<photos.length; i++) {
photos[i].addEventListener("click", () => {
currentState = i
var imageSrc = photos[i].getAttribute("src")
photoModal.style.display = "flex"
//Insert image into the singlePhoto div
singlePhoto.appendChild(img).setAttribute("src", imageSrc)
//Next photo
nextButton.addEventListener("click", () => {
if(currentState < photos.length - 1) {
currentState += 1
console.log("current", currentState, "i", i);
singlePhoto.appendChild(img).setAttribute("src", photos[currentState].getAttribute("src"))
} else {
currentState = 0
console.log("current", currentState, "i", i);
singlePhoto.appendChild(img).setAttribute("src", photos[currentState].getAttribute("src"))
}
})
//Close photo modal/carousel
function closePhoto() {
closePhotoModal.addEventListener("click", () => photoModal.style.display = "none")
}
closePhoto()
})
}
}