Search code examples
javascriptjquerycsscarouselslick.js

Multiple Slick carousels in modal overlays playing at the same time


I have a page with a number of hidden Slick carousels.

To launch a carousel I'd like the user to click a related button and the corresponding slider would show in a modal with a semi-transparent background behind it.

However, when you launch any carousel on the page, all carousels are launched and can be seen autoplaying behind one another.

Here's my HTML:

<button class="launch-gallery">Launch gallery 1</button>
<div class="modal">
  <div class="img-gallery">
  <h2>Gallery 1</h2>
  <div class="img-gallery__slides">
    <div class="img-gallery__slide">
      <img src="image-1.jpg" alt="" />
    </div>
    <div class="img-gallery__slide">
      <img src="image-2.jpg" alt="" />
    </div>
  </div>
</div>

<button class="launch-gallery">Launch gallery 2</button>
<div class="modal">
  <div class="img-gallery">
  <h2>Gallery 2</h2>
  <div class="img-gallery__slides">
    <div class="img-gallery__slide">
      <img src="image-3.jpg" alt="" />
    </div>
    <div class="img-gallery__slide">
      <img src="image-4.jpg" alt="" />
    </div>
  </div>
</div>

Here's my JS to trigger the modal:

var $galleryModal = $('.modal');

$('.launch-gallery').click(function(){

    $galleryModal.toggleClass('is-open');

    return false;
});

Here's my Slick configuration:

var $imgGallery = $('.img-gallery__slides');

$imgGallery.slick({
  infinite: true,
  slidesToShow: 1,
  slidesToScroll: 1,
  dots: false,
  arrows: false,
  accessibility: false,
  cssEase: 'ease',
  autoplay: true,
  autoplaySpeed: 5000,
});

Is there a way to only launch the one carousel related to the button clicked?


Solution

  • Try something like this

    $('.launch-gallery').click(function(){
    
    $(this).next('.modal').toggleClass('is-open');
    
    return false;
    });