1

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";
}
5
  • 1
    I suppose the error is from slides[slideIndex-1].style.display = "block"; . Try console logging your slideIndex just before this line Commented Mar 23, 2018 at 8:01
  • @Zenoo at the very top of the snippet Commented Mar 23, 2018 at 8:01
  • @CertainPerformance Thanks, it slipped through my reading. Commented Mar 23, 2018 at 8:02
  • @Ernest Des-Bordes Do you always have at least one element with class mySlides? Because if you don't then when you are assigning block it will give you an error. Commented Mar 23, 2018 at 8:06
  • @Ernest Des-Bordes please share the html also Commented Mar 23, 2018 at 8:12

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.