I wrote the following code for creating a simple image carousel, that shows multiple images at the same time in the same order, but starting at a different position when the "next" or "prev" button is clicked.
This code works, but does it contradict programming principles and algorithms?
Is there a better solution?
var images = [
"1.jpg",
"2.jpg",
"3.jpg"
];
let slider = document.getElementById("slider");
function next(){
images.forEach((item , index)=>{
if(slider.getAttribute("src") == item)
if(index != images.length-1)
nextIndex = index+1;
else
nextIndex = 0;
});
slider.setAttribute("src",images[nextIndex]);
}
function prev(){
images.forEach((item , index)=>{
if(slider.getAttribute("src") == item)
if(index != 0)
prevIndex = index-1;
else
prevIndex = images.length-1;
});
slider.setAttribute("src",images[prevIndex]);
}
<div>
<button onClick = "prev()"> Prev </button>
<img id="slider" src="1.jpg"
width="200px" height="100px"/>
<button onClick = "next()"> Next </button>
</div>