Reputation: 180
I would like to add a next button to this script instead of having it change images on a timed interval. How would I go about doing this?
Here is the code:
<script src="viewimages.php"></script>
<script type="text/javascript">
var curimg=0
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", ""+galleryarray[curimg])
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0
}
window.onload=function(){
setInterval("rotateimages()", 4500)
}
</script>
<div style="width: 500px; height: 500px">
<img style="width: 100%; height: 100%;" id="slideshow" src="boston1.JPG" />
</div>
Upvotes: 1
Views: 59
Reputation: 3317
You can do this with a button and the onclick event. Use your own rotateimage function and add it with onclick to your html button. The button could be something like that:
<button onclick="rotateimages()">Next</button>
Your hole code:
<script type="text/javascript">
var curimg=0
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", ""+galleryarray[curimg])
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0
}
</script>
<!-- Your new button -->
<button onclick="rotateimages()">Next</button>
<div style="width: 500px; height: 500px">
<img style="width: 100%; height: 100%;" id="slideshow" src="boston1.JPG" />
</div>
Upvotes: 1
Reputation: 207511
You will need to stop and restart the interval. Easier to create a method to do it. And just call the rotateimages like the times does. If you do not want the interval, just get rid of the restartInterval method.
var curimg=0
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", ""+galleryarray[curimg])
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0
}
var _timer;
function restartInterval() {
if(_timer) window.clearInterval(_timer);
_timer = setInterval(rotateimages, 4500)
}
function next() {
restartInterval();
rotateimages();
}
window.onload=function(){
restartInterval();
}
Upvotes: 1
Reputation: 21396
Make a button like this;
<button onclick="rotateimages()">Next</button>
And remove
window.onload=function(){
setInterval("rotateimages()", 4500)
}
from your javascript
The entire code will look like;
<script src="viewimages.php"></script>
<script type="text/javascript">
var curimg=0
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", ""+galleryarray[curimg])
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0
}
</script>
<div style="width: 500px; height: 500px">
<img style="width: 100%; height: 100%;" id="slideshow" src="boston1.JPG" />
</div>
<button onclick="rotateimages()">Next</button>
Upvotes: 1
Reputation: 3624
Remove this:
window.onload=function(){
setInterval("rotateimages()", 4500)
}
And add a button to your HTML:
<button onclick="rotateimages()">Next</button>
Upvotes: 1