Tuesday, 23 October 2018

Custom nav with slick slider going out of sync with carousel slides

I'm using Slick Slider to create a product carousel.

This example shows 4 products in the carousel. As you skip through the slides the nav above the products matches up: Example

This example shows 2 products. It's cloning the slides to make sure there's always 3 on the screen. The problem with this is that the nav above the products goes out of sync when you skip through: Example. Essentially when you're on the cloned slides, when it skips through to the original slides the nav goes back into sync.

How can I get it to match up?

Here's my full code:

    // Category gallery

    // Set preferred slidesToShow
    var slidesToShow = 3; // always 3

    // Clone the slides.
    var $slides = $('.category-gallery .slide');
    if ($slides.length < slidesToShow + 1) {
        var $slide;
        $slides.each( function(){
            $slide = $(this).clone(true)
                .insertAfter( $slide || $slides.last() )
                .addClass('slick-cloned-2')
                .attr('id', '');
        });
    }

    $('.category-gallery').slick({
        dots: false,
        infinite: true,
        slidesToShow: slidesToShow,
        slidesToScroll: 1,
        autoplay: false,
        pauseOnHover:false,
        focusOnSelect: false,
        centerMode:true,
        arrows: true,
    });

    $('a.category-nav[data-slide]').click(function(e) {
        e.preventDefault();
        var slideno = $(this).data('slide');
        $('.category-gallery').slick('slickGoTo', slideno - 1);
    });

    $('a.category-nav[data-slide="1"]').addClass("highlighted-cat-nav");
    $('.category-gallery').on('afterChange', function(event, slick, currentSlide, nextSlide){
        $('a.category-nav').removeClass('highlighted-cat-nav');
      $('a.category-nav[data-slide=' + (currentSlide + 1) + ']').addClass('highlighted-cat-nav');
    });

The problem seems to be on this line:

      $('a.category-nav[data-slide=' + (currentSlide + 1) + ']').addClass('highlighted-cat-nav');



from Custom nav with slick slider going out of sync with carousel slides

No comments:

Post a Comment