Home > Software design >  Slick Slider: Mark custom nav link as active when navigate with arrows
Slick Slider: Mark custom nav link as active when navigate with arrows

Time:02-08

I'm using some custom navigation links for my slick slider to navigate to certain slides.

It works fine but I've a problem if I add the built in arrows from the slider. When I navigate with these, the custom links don't get the .active class.

Is there any way to add this class? I know, that I could use the slider syncing option to do that. But in my case I have to use custom links and couldn't use the asNavFor option.

Here's my current code (working example here: https://codepen.io/cray_code/pen/JjObOPa):

$('.product-gallery').slick({
dots: false,
    arrows: true,
    speed: 300,
    slidesToShow: 1,
    slidesToScroll: 1,
    fade: true,
});

// Custom links
$('a[data-slide]').click(function(e) {
    e.preventDefault();
    var slideno = $(this).data('slide');
    $('.product-gallery').slick('slickGoTo', slideno - 1);
    $('a[data-slide]').removeClass('active');
    this.classList.add('active');
});

Thanks to this answer.

CodePudding user response:

You can use the method afterChange to perform this task. Here is the live demo https://codepen.io/sifat009/pen/bGYgBvP

Here is the javascript code to achieve this.

$('.product-gallery').slick({
    dots: false,
    arrows: true,
    speed: 300,
    slidesToShow: 1,
    slidesToScroll: 1,
    fade: true,
});

$('.product-gallery').on('afterChange', function(event, slick, currentSlide, nextSlide){
  const link = document.querySelector(`.action a[data-slide="${currentSlide 1}"]`);
    $('a[data-slide]').removeClass('active');
    link?.classList?.add('active');
});

$('a[data-slide]').click(function(e) {
    e.preventDefault();
    var slideno = $(this).data('slide');
    $('.product-gallery').slick('slickGoTo', slideno - 1);
    $('a[data-slide]').removeClass('active');
    this.classList.add('active');
});
  •  Tags:  
  • Related