Yucheng Xu Yucheng Xu - 6 months ago 15
HTML Question

JavaScript - Why doesn't my third slide show up?

When I click the prev and next sign, only 1.jpg and 2.jpg img works, 3.jpg never shows up (I can only navigate between 1.jpg and 2.jpg). Console shows no error. I have been look at it for hours, I seriously don't think my code has anything wrong.

CSS:

img {width: 100%;}
#slideshow {position: relative;}
.prev, .next {cursor: pointer;position:absolute; top: 50%;}
.next {left: 99%;}


HTML:

<div id="slideshow">
<a class="prev" onclick="slideshow(-1)">❮</a>
<a class="next" onclick="slideshow(1)">❯</a>
<img src="1.jpg">
<img src="2.jpg">
<img src="3.jpg">
</div>


JavaScript:

function slideshow(n) {
var imgEs = document.getElementById('slideshow').getElementsByTagName('img');
var i = 0, l = imgEs.length;
i += n;
if(i >= l) i = 0;
if(i < 0) i = l - 1;
switch(i) {
case 0:
imgEs[0].style.display = 'block';
imgEs[1].style.display = 'none';
imgEs[2].style.display = 'none';
break
case 1:
imgEs[0].style.display = 'none';
imgEs[1].style.display = 'block';
imgEs[2].style.display = 'none';
break
case 2:
imgEs[0].style.display = 'none';
imgEs[1].style.display = 'none';
imgEs[2].style.display = 'block';
break
default:
imgEs[0].style.display = 'block';
imgEs[1].style.display = 'none';
imgEs[2].style.display = 'none';
}
}
slideshow(0);

Answer

i is a local variable always initialised to be and 0, and it never get to be 2. U need to use a global variable to keep a copy of current active image index.

var activeImgIndex = 0;

function slideshow(n) {
var imgEs = document.getElementById('slideshow').getElementsByTagName('img');
var l = imgEs.length;
activeImgIndex += n;
if(activeImgIndex >= l || activeImgIndex < 0) {activeImgIndex = 0;}
switch(activeImgIndex) {
    case 0:
        imgEs[0].style.display = 'block';
        imgEs[1].style.display = 'none';
        imgEs[2].style.display = 'none';
        break
    case 1:
        imgEs[0].style.display = 'none';
        imgEs[1].style.display = 'block';
        imgEs[2].style.display = 'none';
        break
    case 2:
        imgEs[0].style.display = 'none';
        imgEs[1].style.display = 'none';
        imgEs[2].style.display = 'block';
        break
    default:
        imgEs[0].style.display = 'block';
        imgEs[1].style.display = 'none';
        imgEs[2].style.display = 'none';
    }
}
slideshow(0);