简体   繁体   中英

Why my Jquery carousel doesn't stop at the last image?

I am trying to make build my own carousel from scratch since I cant find a plugin that does what I want. Which is having a vertical and horizontal plugin that work at the same time both ways.

Anyway I decided to give it a shot and try to build my own. But right now I am stuck at trying to understand why my "next" button doesn't disappear when it has reached the end of the carousel.

here is the code:

$(document).ready(function() {
    var sliderWidth = 300; // Give the size of the window
    var sliderV = $('#slide-wrap-vertical'); // Assigns the container that has all the sectiosn that will be scrolled vertically
    var sliderCount = $(sliderV).children().size(); // Gets the size of the verticla slider

    //test();

    $('a.nav-top-prev').on('click',function () {

        $('#slide-wrap-vertical > div').animate({
            top: '+=' + sliderWidth
        }, 500);
        showHideDirection();

    });

    $('a.nav-top-next').on('click', function () {
        $('#slide-wrap-vertical > div').animate({
            top: '-=' + sliderWidth
        }, 500);
        showHideDirection();

    });


    function showHideDirection() {

        $(sliderV).children().each(function(){ // Checks all the children of the vertical carousel


            if ($(this).position().top == 0) { // Finds the index of the children that is currently on view

                if ($(this).index() == 0) { // If its the first one can't scroll back and hides the prev button

                    $('a.nav-top-prev').hide();

                }

                else if ($(this).index() >= sliderCount) { // If its the last one can't scroll forward and hides the next button

                    $('a.nav-top-next').hide();

                }

                else {

                    $('a.nav-top-prev').show();
                    $('a.nav-top-next').show();

                }
            }   

        });
    }


});

http://jsfiddle.net/Dethdoll/WkFVs/8/

because sliderCount is 1 based and index() is zero based, it is impossible for index to be equal or greater than sliderCount. You need to subtract one.

else if ($(this).index() === sliderCount-1)

You can simplify those if/else checks with toggle

if ($(this).position().top == 0) {
    var index = $(this).index();
    $('a.nav-top-prev').toggle(index!==0);
    $('a.nav-top-next').toggle(index!==sliderCount-1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM