steve Kim steve Kim - 5 months ago 18
jQuery Question

JS completing slideshow function

For js slideshow, I have been trying to make it work as follow:

When first loaded: three images total

<div class="images" style="display:block;"><img src="img_1.jpg"></div>
<div class="images" style="display:none;"><img src="img_2.jpg"></div>
<div class="images" style="display:none;"><img src="img_3.jpg"></div>

<a class="prev" onclick="moveSlides(-1)">❮</a>
<a class="next" onclick="moveSlides(1)">❯</a>


When images are first loaded, the first image has
display:block
while other two had
none
by default.

//when next/prev button is clicked
function moveSlides(n) {
slideShow(n);
};

function slideShow(n) {
var slides = document.getElementsByClassName("images");

// Display none for current image
for (var i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}

// display block for next image
slides[n].style.display = "block";

};


The idea is that when the
next
or
prev
button is clicked, it will turn every image into
display:none
then change the next image to
display:block
.

I am having a bit of hard time accomplishing following things:


  1. Detecting what image is currently being displayed so that when either
    next
    or
    prev
    button is clicked, it knows which image to display.

  2. When it goes through the last image, it should go back to the first image.

  3. Any other issues?


Answer

First, I'd recommend using a CSS class to control which one is visible:

.images         { display: none; }
.images.visible { display: block; }

That way you can use it as a selector in the JS to find which one was previously visible before you switch to the new one.

You can also use nextElementSibling and previousElementSibling to find the element that should be visible next.

function slideShow(n) {
    var slide = document.querySelector('.images.visible');
    slide.classList.remove('visible');
    if (n > 0) {
        if (slide.nextSibling) {
            slide.nextSibling.classList.add('visible');
        } else {
            document.querySelector('.images').classList.add('visible');
        }
    } else {
        if (slide.previousSibling) {
            slide.previousSibling.classList.add('visible');
        } else {
            var slides = document.querySelectorAll('.images');
            slides[slides.length - 1].classList.add('visible');
        }
    }
}

This avoids using a loop or selecting more than you need, except in the case that it needs to wrap around to the beginning or end.