Ernest Des-Bordes
Ernest Des-Bordes

Reputation: 23

Cannot read property 'style' of undefined in Javascript Function

I have this Javascript function butwhen i run it it says 'Cannot read property 'style' of undefined at showSlides'

 var slideIndex = 1;
showSlides(slideIndex);

// Next/previous controls
function plusSlides(n) {
  showSlides(slideIndex += n);
}

// Thumbnail image controls
function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = 1} 
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none"; 
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block"; 
  dots[slideIndex-1].className += " active";
}

Upvotes: 1

Views: 619

Answers (1)

Dathan
Dathan

Reputation: 4553

if (n < 1) {slideIndex = slides.length - 1}

slideIndex cannot be slides.length, The last element of slides will be present at slides.length - 1, not slides.length.

Upvotes: 2

Related Questions