how to loop through an array elements one by one on event listener

Viewed 26

I'm a self-learner of JS. I need a hand. I want to make a private project of a background-slider as a click event. Let's say I have 3 backgrounds in the image folder: bgr1.jpg, bgr2.jpg, bgr3.jpg. I can put them into an array and loop through them, but I want to loop through them one by one and I need to add the condition that when loop reaches the last one, it starts from element [0]. I know that for some it may be a piece of cake but I'm feeling stuck. I can only list the array items all at the same time, but can anyone show how to display them one by one. I would appreciate.

  <button id="btn">Next</button>
  const backgrounds = ["bgr1.jpg", "bgr2.jpg", "bgr3.jpg"];
  const btn = documentQuerySelector("#btn");
  btn.addEventListener("click", function() {
  for(let i=0; i<backgrounds.length; i++) {
    console.log(backgrounds[i]);
}

  // document.body.style.backgroundImage = ... (?)

})



1 Answers

Based on my previous answer from today.

var AIPic = [
  "https://picsum.photos/id/200/200",
  "https://picsum.photos/id/201/200",
  "https://picsum.photos/id/202/200"
]
SelectedImage = 0;
document.querySelector("#btn").addEventListener("click", function() {
  document.getElementById('AIPics').src = AIPic[SelectedImage];
  SelectedImage++
  if (SelectedImage >= AIPic.length) {
    SelectedImage = 0;
  }
})
<button id="btn">Next</button><br>
<img id="AIPics">

Related