Search code examples
javascripthtmlcssfrontendslick.js

Sync images with Slick Carousel


Basically I'm using https://kenwheeler.github.io/slick/ for this

I've read the Slick documentation and indeed there is a sync option but available only with another slide. Is it possible to link images to show with the slide ?

Thank you in advance.

JS code of the slide :

$(function(){ 
        
$('.center').slick({
    centerMode: true,
    centerPadding: "0px",
    slidesToShow: 8,
    arrows:false,
    autoplay:false,
    infinite:false,
    responsive: [
      {
        breakpoint: 768,
        settings: {
          arrows: false,
          centerMode: true,
          centerPadding: '40px',
          slidesToShow: 3
        }
      },
      {
        breakpoint: 480,
        settings: {
          arrows: false,
          centerMode: true,
          centerPadding: '40px',
          slidesToShow: 1
        }
      }
    ]
  });
  
});

Solution

  • You can use the afterChange() and beforeChange() events to trigger any JavaScript that you want. For instance, you can write a function to toggle other images to show like this:

    HTML

    <img id="image0" class="hero-image" src="..." />
    <img id="image1" class="hero-image" src="..." />
    <img id="image2" class="hero-image" src="..." />
    

    CSS

    // Hide all images to start
    .hero-image {
      display: none;
    }
    

    JavaScript

    // Show the current slide's corresponding image after the slide is shown
    $('.center').on('afterChange', function(event, slick, currentSlide){
      $('.hero-image').hide();
      $(`image${currentSlide}`).show();
    });