I've been trying to fix this for a long time and it's really annoying me as its a simple issue I just can't figure it out, I am trying to make a next-previous style image viewer but when I press the next button a couple of times and view all images it takes two clicks to cycle to the next image, any help would be great, The code may not be in the greatest format or be very efficient so any advice on that would be appreciated greatly, thank you.
HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="./mainImage.css">
<title>Image Gallery</title>
</head>
<body>
<div >
<img id='image1' src="">
<button onclick="next()">next</button>
<!--<button onclick="prev()">prev</button>-->
<p id='check'>gf</p>
</div>
</body>
</html>
- Javascript:
var images = [
"cow.PNG",
"del.PNG",
"falafel.PNG"
]
var count = 0;
var dis = document.getElementById('image1')
function loadImg(imgIndex){
dis.src=images[imgIndex];
}
function next(){
if(count >= 0 && count < images.length){
loadImg(count);
count ;
} else {
count=0;
loadImg(count);
}
}
window.onload = next()
CodePudding user response:
It happens because of different order in branches of condition operator in your next()
function. When your counter is more than length of array you first set counter to 0 and then load an image, but on the next click you first load the image with 0 index and only then increment the counter, probably better to simplify your function e.g. like this:
function next() {
count ;
if (count == images.length) count = 0;
loadImg(count);
}
and call loadImg()
function when page has been loaded:
window.onload = loadImg(count);