Reputation: 111
I've used W3School for this slideshow and I have it very similar, given that I've changed a few class names and ID names. However, my slideshow won't move past the second image nor will it go into a loop. I've looked at the other answered questions similar to this one, but have not found the answer.
Html
<!-- Create: slider -->
<h1>Noticias Relevantes</h1>
<div class="slide-container">
<div class="fade">
<div id="num-txt">1 / 3</div>
<img src="img\greenery.jpg">
<div class="text">Nuevo viaje...</div>
</div>
<div class="fade">
<div id="num-txt">2 / 3</div>
<img src="img\snow.jpg">
<div class="text">Expansion a nuevo paises...</div>
</div>
<div class="fade">
<div id="num-txt">3 / 3</div>
<img src="img\pink-church.jpg">
<div class="text">Nuevo contrato con iglesia...</div>
</div>
</div>
<div class="dots">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
<!-- Date -->
</div>
<div id="information">
<h1>Informacion Importante</h1>
<div id="infoList">
<!-- Create: Drop down list -->
</div>
</div>
<!--Right menu w/images as links -->
</body>
<script src="main.js"></script>
</html>
Javascript
// @ts-check
var slideIndex = 0;
showSlides();
function showSlides() {
var i;
var slides = document.getElementsByClassName("fade");
var dots = document.getElementsByClassName("dots");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {
slideIndex = 1;
}
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";
setTimeout(showSlides, 2000); //changes img every.
}
If it's possible please give a detailed explanation, I'd like to know as to why my code is wrong.
Thank you.
Upvotes: 1
Views: 91
Reputation: 138267
To make it work just change dots
to dot
. However, we could rewrite the code a bit to make it reusable / more bulletproof:
function showSlides(slides, dots) {
if(slides.length !== dots.length) throw new Error("mismatch of element length");
var slideIndex = 0;
(function next(){
for (i = 0; i < slides.length; i++) {
slides[i].style.display = i === slideIndex ? "block" : "none";
if( i === slideIndex ){
dots[i].classList.add("active");
}else{
dots[i].classList.remove("active");
}
}
slideIndex = (slideIndex + 1) % slides.length;
setTimeout(next, 2000);
})()
}
To start it do:
showSlides(
document.getElementsByClassName("slides"),
document.getElementsByClassName("dot")
);
Or using jquery ( maybe ):
showSlides( $(".slides"), $(".dot"));
Upvotes: 1