Rain Rain - 3 months ago 19
HTML Question

Automatic Slideshow not stop when i use javascript event

I wrote a script to make an automatic slideshow, and i want it to stop when i onlick (or onmouseover) the image (or the content) but it not work for me. Someone please show me if there're any error in my code. Thank you!

This is my code:



var slideIndex =1;
showslides(slideIndex);
function plusslide(n){
showslides(slideIndex+=n);
};
function showslides(n){
var i;
var slides = document.getElementsByClassName("fade");
if (n>slides.length){ slideIndex=1};
if(n<1){slideIndex=slides.length};
for (i=0; i<slides.length; i++){
slides[i].style.display = "none";
}
slides[slideIndex-1].style.display = "block";
};

var interval=setInterval(function(){slideIndex+=1; showslides(slideIndex);},1000);
document.getElementsByClassName("fade").onclick=function(){stop()};
function stop(){
clearInterval(interval);
};

<body>
<div class="page">
<div class="container">
<div class="content">
<div class="fade">
<img src="#" />
<p>1/3</p>
</div>
<div class="fade">
<img src="#" />
<p>2/3</p>
</div>
<div class="fade">
<img src="#" />
<p>3/3</p>
</div>
<a class="prev" onclick="plusslide(-1)">&#10094;</a>
<a class="next" onclick="plusslide(1)">&#10095;</a>
</div>
</div>
</div>
<script type="text/javascript" src="slide.js"></script>
</body>




Answer

There's a small typo in your code. Replace getElementsbyClassName with getElementsByClassName.

You can catch errors like this in the future by using your browser's developer console, where it will tell you where's an error in your code and what type. Just search for Developer Tools, it will help you find and fix errors like this yourself.

Edit:

Oh yes, didn't see that one. There is indeed also an error in this line:

document.getElementsByClassName("fade").onclick=function(){stop()};

Here's the issue. getElementsByClassName does not return a DOM element, but rather an array of elements, since there are multiple elements with that class name. You'll have to loop through each one in order to access onclick on them, just like you did in your function above, like this:

var slides = document.getElementsByClassName("fade");
for (var i = 0; i < slides.length; i++) {
    slides[i].onclick = stop;
}

Also, small sidenote: I shortened function(){stop()} to just stop in my answer. Since you only call that function without any arguments in onclick, you can just directly bind stop to onclick.

Comments