patrick.altair patrick.altair - 6 months ago 16
jQuery Question

How to count backward through a variable in js?

I'm making a simple slide show with a left and right arrow that navigates through list items with imgs inside. I've got the right arrow working to progress through the list but cannot get the left arrow to go backward through the list. It seems to just randomly jump to the last slide after being clicked. How can I count backward through the variable to show the last slide?

Codepen here: http://codepen.io/patrickaltair/pen/oxrZVg

Relevant js:

$( document ).ready(function() {

var slide = $('.slide');
var slideIndex = -1;


function showFirstSlide() {
// Add 1 to slide index
slideIndex++;
slide.eq(slideIndex % slide.length)
.fadeIn(1000);
}

showFirstSlide();


$('.right').click(function(){

function showNextSlide() {
// Add 1 to slide index
slideIndex++;
slide.eq(slideIndex % slide.length)
.fadeIn(1000);
}

showNextSlide();

});

$('.left').click(function(){

function showPreviousSlide() {
// Substract 1 from slideIndex
slideIndex--;
slide.eq(slideIndex % slide.length)
.fadeIn(1000);
}

showPreviousSlide();

});

});

Answer

I did manage to fix your code by adding a fadeOut when changing the image.

Probably when clicking the left arrow the second image was on top of the first so you could not see the correct image

$( document ).ready(function() {

    var slide = $('.slide');
    var slideIndex = -1;


    function showFirstSlide() {

            // Add 1 to slide index

            slideIndex++;

            slide.eq(slideIndex % slide.length)
                .fadeIn(1000);
        }

        showFirstSlide();


    $('.right').click(function(){

        function showNextSlide() {

            // Add 1 to slide index
        slide.eq(slideIndex % slide.length).fadeOut(1000);
            slideIndex++;
            slide.eq(slideIndex % slide.length)
                .fadeIn(1000);
        }

        showNextSlide();

    });

    $('.left').click(function(){

        function showPreviousSlide() {
                    // Add 1 to slide index
        slide.eq(slideIndex % slide.length).fadeOut(1000);
            slideIndex--;
            slide.eq(slideIndex % slide.length)
                .fadeIn(1000);
        }

        showPreviousSlide();

    });

});
Comments