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;
}
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";
}
<div class="slideshow-container">
<div class="mySlides fade">
<img src="https://picsum.photos/200/300?grayscale" style="width: 100%">
</div>
<div class="mySlides fade">
<img src="https://picsum.photos/200/300" style="width: 100%">
</div>
<div class="mySlides fade">
<img src="https://picsum.photos/200/300?grayscale" style="width: 100%">
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<div style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
caught TypeError: Cannot read properties of undefined (reading 'style')
at showSlides (sam.js:25:26)
at sam.js:2:1
5sam.js:26 Uncaught TypeError: Cannot read properties of undefined (reading 'className')
at showSlides (sam.js:26:9)
at plusSlides (sam.js:5:5)
at HTMLAnchorElement.onclick (VM229 index.html:1:1)
I tired to change the class name and delete the style tag in javascript the part of the line it saying it causing issue. i thought might be css and so i mess with css that causing it but it still giving that error message and some time when refresh the browser there are no image displaying and when i hit next arrow it activates the images and able to click next and change images but somehow it give that error and the images wont display load up when load the website first time or hitting refresh
2
Answers
These two operations are doing more than you think:
By changing the entire text of the
className
, you’re effectively modifying the live HTML collection result of this:Which means the length of that collection changes. You can observe this by logging some debugging information to the console:
Instead of directly replacing the
className
property, make use of theclassList
API:This will allow the rest of the classes to remain unaffected, which in turn won’t affect the
HTMLCollection
object over which you’re iterating.Here’s your solution, when adding a new class using as a string, make sure you separate them by space in
dots[slideIndex - 1].className += " active";
. Also, you didn’t check ifslideIndex
is less than1
and I added this condition in theshowSlides(n)
function.