<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" type="text/html" charset="UTF-8"/>
<style>
*{margin:0; padding:0;}
.mySlides{
position:relative;
width:1000px;
margin:40px auto;
display:table;
}
.number{
position:absolute;
margin:20px;
}
.text{
position:absolute;
bottom:20px;
text-align:center;
width:100%;
}
.prev, .next{
position:absolute;
top:40%;
background-color:black;
color:white;
padding:20px;
cursor:pointer;
user-select:none;
}
.next{
right:0;
}
.text-align{
text-align:center;
}
.dot{
width:30px;
height:30px;
background-color:gray;
display:inline-block;
}
.dot.active, .dot:hover{
background-color:orange;
}
</style>
</head>
<body>
<div class="mySlides">
<div class="number">1/4</div>
<img src="images/slide1.jpg" width="100%"/>
<div class="text">Text 1</div>
</div>
<div class="mySlides">
<div class="number">2/4</div>
<img src="images/slide2.jpg" width="100%"/>
<div class="text">Text 2</div>
</div>
<div class="mySlides">
<div class="number">3/4</div>
<img src="images/slide3.jpg" width="100%"/>
<div class="text">Text 3</div>
</div>
<div class="mySlides">
<div class="number">4/4</div>
<img src="images/slide4.jpg" width="100%"/>
<div class="text">Text 4</div>
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
<div class="text-align">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
<span class="dot" onclick="currentSlide(4)"></span>
</div>
<script>
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";
}
</script>
</body>
</html>
Is there a way to change the image/slider every 3 seconds using JavaScript?
I've tried using setTimeout(showSlides, 3000); but what additional code do I need to add?
When I use slideIndex++; and setTimeout(showSlides, 3000); the slider changes every 3 seconds, but the slider buttons don't match with the images. Any suggestions on how to sync the slider buttons with the images?