I have an Image carousel that contains three images. I have next and previous buttons to click through the array of images, but I would like it to go back to the first image when clicking 'next' on the last image in the array (and to the last one when clicking 'previous' on the first image). Is there a way I can use a loop to make this work?
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var currentImg = 0;
document.querySelector('.carousel>img').src = 'images/' + images[0];
document.querySelector('.carousel').addEventListener('click', function (evt){
var target = evt.target;
if (target.classList.contains('control')) {
if (target.classList.contains('next')) {
//move to the next index in the array
currentImg += 1;
} else if (target.classList.contains('prev')){
// move to the previous index in the array
currentImg -= 1;
}
// display the new current image
document.querySelector('.carousel>img').src = 'images/'
+ images[currentImg];
}
});
I was able to do the following and it did what I wanted:
if (target.classList.contains('next')) {
if(currentImg==2){
currentImg=0
} else {
currentImg += 1;
}
} else if (target.classList.contains('prev')){
if(currentimg==0){
currentimg=2
} else {
currentImg -= 1;
}
Thank you for all the other suggestions I will look into those as well!