0

I got an Image-Slider in a website and in the Console, there is the following Error-Message:

Uncaught TypeError: Cannot read properties of undefined (reading 'style') at showSlides (Script.js:64) at Script.js:40

showSlides @ Script.js:64, (anonymous) @ Script.js:40

The Error dosent affect the slider in any way, but i want to fix it.

JavaScript Code:

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("sliderImage");
  var dots = document.getElementsByClassName("imageSliderDot");
  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";
}
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Eugene
  • 17
  • 6
  • 1
    What is the value of `slideIndex` and `n` when this happens? How do they compare to `slides.length`? – Barmar Nov 05 '21 at 20:12
  • This error might occurs because your script is running before your elements load on the page. Print `slides` and `slideIndex` before `slides[slideIndex-1].style.display = "block";` and see what it tells you. – Pedro Blandim Nov 05 '21 at 20:18
  • 1
    To solve that part, load your script with ``, where the `async` attribute makes sure your JS gets downloaded without blocking the page parser, and the `defer` attribute makes sure it won't actually _run_ until your DOM is ready for reading (but before DOMContentLoaded fires, so event bindings for that keep working). – Mike 'Pomax' Kamermans Nov 05 '21 at 20:24
  • 1
    Please do not add SOLVED in the title. We don't do that here. If you found an answer then post it as a solution in the answer space below. If the problem is not reproducible anymore due to a typo or misunderstanding then you can delete the question – Dharman Nov 07 '21 at 14:19

0 Answers0