Paul Galaxys
Paul Galaxys

Reputation: 11

How to add automatic slideshow to the JavaScript slider for 10 seconds?

I tried to add setTimeout(showSlides, 10000); but it is not working. What the best way to do automatic slideshow without making lag on the page?

var slideIndex = 1;
showSlides(slideIndex);

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

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

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

Upvotes: 0

Views: 630

Answers (1)

Mindaugas Kurlys
Mindaugas Kurlys

Reputation: 66

This default approach might be helpful.

<!DOCTYPE html>
<html>

<body>
<div style="max-width:500px">
  <img class="mySlides" src="your image url" style="width:100%">
  <img class="mySlides" src="your image url" style="width:100%">
  <img class="mySlides" src="your image url" style="width:100%">
</div>

<script>
var myIndex = 0;
carousel();

function carousel() {
  var i;
  var x = document.getElementsByClassName("mySlides");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";  
  }
  myIndex++;
  if (myIndex > x.length) {myIndex = 1}    
  x[myIndex-1].style.display = "block";  
  setTimeout(carousel, 2000); // Change image every 2 seconds
}
</script>

</body>
</html>

Upvotes: 1

Related Questions