Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I fix TypeError: Cannot read properties of undefined (reading 'style')

I have a slideshow carousel that allows you to select dots to navigate images, and hit arrows to navigate back and forth, but when the site loads the first image is shown and requires you to select the circle corresponding to the image or cycle through all of the images with the arrows for the image to be shown. Does it have anything to do with the TypeError I’m receiving? How can I fix this?

Javascript Code

let slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  let i;
  let slides = document.getElementsByClassName("mySlides");
  let 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";
}

I’ve tried a lot of things so far but I’m not necessarily advanced enough in javascript to understand the issue.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The error TypeError: Cannot read properties of undefined (reading ‘style’) occurs because one of your slides[n] comes in empty. I assume that you have defined <script> js incorrectly. Is your script at the very end of the <body/>?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading