JavaScript SlideShow Code Question

I’m watching TraverstyMedia on YouTube (great channel for learnging btw), and his code (seemingly, to me) randomly declares “i” in the middle of his js code. Current already = 0, so is he saying that i = current, as well?

Also, I’ve seen i used before in similar slideshow js. Is there something special about it, or is it just the default more or less because i is the first letter of image? These are the first two bits of code.

Thanks for any help offered!

let sliderImages = document.querySelectorAll(".slide"),
arrowLeft = document.querySelector("#arrow-left"),
arrowRight = document.querySelector("#arrow-right"),
current = 0;

// Clear all images
function reset() {
for (let i = 0; i < sliderImages.length; i++) {
sliderImages[i].style.display = “none”;
}
}

This is his full code btw:
https://codepen.io/bradtraversy/pen/boydaE

The variable i is only used inside the for loop of the reset function. That is not random. He is just wanting to iterate through all the divs with class=“slide” and hide them. The let is only valid for that for loop block of code and can not be accessed outside of it. It has nothing to do with the other variable named current which is responsible for keeping track of the current slide.

1 Like

Another approach using almost the same CSS is to make add display:none to the slide class. This will make all of the slides hidden by default when the page loads.

Then you can do something like the following for the JavaScript. You will notice there is hardly any repetitive code as the original code had and has almost half of the number of lines as before. There is no need for a reset function which iterated through all the slides. Now, when either of the arrows is clicked, only the current slide is hidden and the next slide (which ever direction) is shown.

let sliderImages = document.querySelectorAll(".slide"),
  arrowLeft = document.querySelector("#arrow-left"),
  arrowRight = document.querySelector("#arrow-right"),
  current = 0;

function showSlide(index, show) {
  const display = show ? "block" : "none";
  sliderImages[index].style.display = display;
}

// Show prev
function changeSlide(direction) {
  showSlide(current, false);
  current += direction;
  const remainder = current % sliderImages.length;
  current = Math.floor(remainder >= 0 ? remainder : remainder + sliderImages.length);
  showSlide(current, true);
}

// Left arrow click
arrowLeft.addEventListener("click", changeSlide.bind(null, -1));

// Right arrow click
arrowRight.addEventListener("click", changeSlide.bind(null, 1));

// Init slider
showSlide(0, true);
1 Like

Randell, thank you so much for your great response. I’m sorry it took so long to get back to you. I had a response ready but got distracted. Have since learned more about loops and it makes a lot more sense.