Search code examples
javascriptcarousel

Could you explain this simple image slider code line by line?


Are you able explain this simple image slider code line by line?

I'm particularly interested in where the n and no values come from in currentSlide(no) + plusSlides(n).

var slideIndex = 0;
var slides = document.getElementsByClassName("mySlides");
var interval;
var pauseButton = document.getElementById("pause");

showSlides();
playSlideshow();

function showSlides() {
  var i;
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {
    slideIndex = 1;
  }
  slides[slideIndex - 1].style.display = "block";
}
// Manual control 
function currentSlide(no) {
  var i;
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex = no;
  slides[no - 1].style.display = "block";
}

function plusSlides(n) {
  var newslideIndex = slideIndex + n;
  if (newslideIndex < 6 && newslideIndex > 0) {
    currentSlide(newslideIndex);
  }
}

Edited to add rest of the code.

// Pause

var playing = true;

function pauseSlideshow() {
  var pauseButton = document.getElementById("pause");
  pauseButton.innerHTML = "&#9656;";
  playing = false;
  clearInterval(interval);
}

function playSlideshow() {
  pauseButton.innerHTML = "&#x23F8;";
  playing = true;
  interval = setInterval(showSlides, 5000);
}

pauseButton.onclick = function () {
  if (playing) {
    pauseSlideshow();
  } else {
    playSlideshow();
  }
};

As per the comments, I have added additional code.


Solution

  • Yes, can do!

    The first function showSlides is called. It first makes every element with the mySlides class invisible (basically hides all your slides). Then it increments the slide index and checks to see if the index is over the total amount of slides so it can start from the beginning again. Finally it shows the slide that the index is referring to.

    The currentSlide function sets the active slide to the index provided in the no argument. First it hides all the slides and then sets the new slide index to what no is and then shows that slide.

    Finally plusSlides goes forward (or backwards if using a negative number) n slides. The if statement checks if the index is between 1 and 5. If it is the slide that corresponds with the new index is shown.

    A few notes

    • for loops can be written without a variable declaration preceding it like this
    for(let x = 0; x < 100; x++){
        console.log(x);
    }
    
    • In your plusSides function, you check for a specific range, but you could base it off of the amount of slides with slides.length like in showSlides. Also, I would recommend making sure that if the index does happen to fall out of this range to set the index to a default value.
    if (newslideIndex < slides.length && newslideIndex > 0) {
        currentSlide(newslideIndex);
    } else {
        currentSlide(1);
    }
    

    That is all!