Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinity slider previous button logic not working

I'm trying to create an infinity slider using jQuery. The active slide will be 2/3 of the screen, the upcoming slide will be 1/3. So you already see a preview of the next slide.

The slider that I've build is working. When you click next the slider will be animated to the left.

The trick

On init I duplicate the first two slides after the last slide. When slideIndex, that keeps an eye on the current index, is the number of slides minus 1, it will reset the slider to zero. So you've an infinity slider.

Problem

The problem comes when I also want to apply the effect when you're at the first slide and click previously. It should basically do the same, but not reset the slider to zero, but to the end of the slides.

var slider = $('.slider');
var slides = slider.find('.slides').children();
var slidesW = slides.width();

root.offset = -Math.abs((root.slideIndex * slides.eq(index).width()));
console.log(root.offset);

// Update active class
slides.removeClass('active');
// slides.eq(index).addClass('active');

// Add class active
TweenMax.to(slides.eq(index), 1, {
    className: 'active', 
    onComplete: function() {

        if (root.slideIndex >= (root.numOfSlides - 2)) {

            slider.find('.slides').addClass('no-transition');

            slides.removeClass('active');
            slides.filter(':first').addClass('active');

            root.offset = 0;

            TweenMax.set(slider.find('.slides'), {
                x: root.offset, 
                onComplete: function() {
                    root.slideIndex = 0;
                    $('#footer .paging #indicator').find('span').html('01');

                    return false;
                }
            });

        } 
    }
});

// Remove no-transition class
slider.find('.slides').removeClass('no-transition');

// Change position of ul.slides
TweenMax.to(slider.find('.slides'), 0.4, {
    x: root.offset
});

Because I have an if statement of if (root.slideIndex === (root.numOfSlides - 2)) { it will always be resetting to zero, when slideIndex is equal to root.numOfSlides - 2. So its doesn't matter if you click previous or next, when slideIndex is in my example at slide 4, it will reset to zero.

I recreate the slider in a codepen: https://codepen.io/anon/pen/zEmozr

like image 429
Caspert Avatar asked Nov 07 '22 15:11

Caspert


1 Answers

Change this line:

if (dir == "ss-prev") {
    // root.slideIndex--;
    root.slideIndex = (root.slideIndex - 1 < 0) ? root.numOfSlides - 1 : root.slideIndex - 1;
    console.log('prev', root.slideIndex);
}

By:

if (dir == "ss-prev") {
    // root.slideIndex--;
    root.slideIndex = (root.slideIndex - 1 < 0) ? root.numOfSlides - 3 : root.slideIndex - 1;
    console.log('prev', root.slideIndex);
}

https://codepen.io/anon/pen/xXBMZJ?editors=1111

like image 101
jd_7 Avatar answered Dec 08 '22 00:12

jd_7