i just made a simple slideshow which changes images automatically and also has manual option so you can go forward and backward with images when you want.
Here is the problem: Auto function which changes the images is set to every 3 seconds. But if you for example click to change the slide after 2.5 seconds,the slide will change, but after 0.5 seconds auto function will also change to the next slide.
So i other way,auto function is interrupting manual change, is there any way to reset autofunction after the slideshow is changed manually?
here is the html code:
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Chapter 11 - HTML Forms and JavaScript</title>
</head>
<body onload="autoRun()">
<img src="slika1.jpg" id="slideshow" width="700px",
height="350px">
<br/>
<p id="caption">slika1</p>
<a href="#" id="buttonNext">Next Slide</a><br/>
<a href="#" id="buttonPrevious">Previous Slide</a>
<script src="slideshow.js"></script>
</body>
</html>
JS code:
document.getElementById('buttonNext').onclick=function(){
changeImage(1);
return false;
}
document.getElementById('buttonPrevious').onclick=function(){
changeImage(-1);
return false;
}
var images =["slika1.jpg","slika2.jpg", "slika3.jpg" ];
var caption=["slika1", "slika2", "slika3"];
var imageNumber=0;
var imageLength=images.length -1;
function changeImage(x){
imageNumber+=x;
if(imageNumber > imageLength){
imageNumber = 0;
}
if(imageNumber < 0){
imageNumber = imageLength;
}
document.getElementById('slideshow').src=images[imageNumber];
document.getElementById('caption').innerHTML=caption[imageNumber];
return false;
}
function autoRun(){
setInterval("changeImage(1)", 3000);
}
This is quite easy to do.
1) Add a global variable var timer;
2) At the start of your changeImage()
function, add this: autoRun();
3) Change your autoRun()
function to this:
function autoRun(){
clearTimeout(timer);
timer = setTimeout("changeImage(1)", 3000);
}
This way the autorun-timer is reset everytime changeImage()
is invoked, whether that happens because you manually changed the slide or the autorun-function did.