I am making a slideshow that uses JSON data to populate it's contents. When I come to the last slide I have to click 2-3 times before the slideshow starts on the first slide again. I want to make sure this doesn't happen and one click is enough to start on the first slide again. A similar bug is when I first load the page and click on the back button for the first time i have to click twice, after that it works as it should. I am sure there is a problem in one of my if statements, but I can't figure out whats wrong.
index.html
<div class="slideshow-container">
<div class="mySlides fade">
<img id="image" style="width:100%">
<div id="description"></div>
</div>
<a id="prev">❮</a>
<a id="next">❯</a>
</div>
<script>
window.onload = startup;
var xmlhttp;
function startup () {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = statechange;
xmlhttp.open("GET", "slideshow.json", true);
xmlhttp.send();
}
function statechange() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var printout = "";
var doc = JSON.parse(xmlhttp.responseText);
var amountOfElements = doc.length;
var current = 0;
var imagePath = "assets/stop2/";
document.getElementById("image").src = imagePath + doc[current].image;
document.getElementById("description").innerHTML = doc[current].text;
console.log(current);
prev.onclick = function() {
if(current !== 0){
current = current - 1;
document.getElementById("image").src = imagePath + doc[current].image;
document.getElementById("description").innerHTML = doc[current].text;
if(current === 0) {
current = amountOfElements;
}
}
else {
current = amountOfElements;
}
console.log(current);
};
next.onclick = function() {
if(current < amountOfElements) {
current = current + 1;
document.getElementById("image").src = imagePath + doc[current].image;
document.getElementById("description").innerHTML = doc[current].text;
}
else {
current = -1;
}
console.log(current);
};
}
else if (xmlhttp.readyState === 4 && xmlhttp.status === 404) {
alert("Something went wrong");
}
}
</script>
slideshow.json
{
"name": "First image",
"text": "blablabla",
"image": "img1.png",
"audio": "audio1.mp3"
},
{
"name": "Second image",
"text": "Lorem ipsum..",
"image": "img2.png",
"audio": "audio2.mp3"
},
{
"name": "Third image",
"text": "blablabla",
"image": "img3.png",
"audio": "audio3.mp3"
},
{
"name": "Last image",
"text": "blablablaaaaaa",
"image": "img4.png",
"audio": "audio4.mp3"
}
] ```