0

I am trying to get one flickity carousel to work in each of my accordion items and my lack of knowledge in js gets me unfortunately to a dead end. What happens is that I see my carousels broken (not working) inside my accordion items until I slightly resize my viewport. Then the one that is open adjusts itself, while the others remain broken.

My js looks like that at the moment:

$(document).ready(function(){
  $('.event-carousel').flickity({
    cellAlign: 'left',
    setGallerySize: false,
    freeScroll: true,
    wrapAround: true,
    prevNextButtons: false,
    pageDots: false
  });

  $('.accordion__item').on('click', function() {
    var $this = $(this);
    if ($this.hasClass('collapsed')) {
      $('.accordion__item').addClass('collapsed');
      $this.removeClass('collapsed');
    } else {
      $this.addClass('collapsed');
    }
  });
}

While my html is so:

          <div class="event-carousel">
            <?php foreach ($slides as $slide): 
              $img     = $slide->image()->toFile();
            ?>
            <div class="carousel-cell">
              <?= $img->thumb(['format' => 'webp']) ?>
            </div>
            <?php endforeach ?>
          </div>
      </div>

My gut feeling tells me that somehow I should tell my js to initialise or destroy the carousel everytime these classes are added or removed.

Could anyone give me a lesson here? Thank you!

1 Answers1

0

Do you only want to initialize them when you open the Accordion? Then you have to initialize and destroy them everytime.

I for myself initialize the Sliders all at once. Because you toggle the Accordion just by toggling classes the Sliders should work while they're hidden as well. So there is no need to reinitialize and destroy them.

That means you just need to init all Flickities all at once, i do it like so:

const FLICKITIES = document.querySelectorAll('.event-carousel');

FLICKITIES.forEach((slider) => {
    new Flickity(slider, {
        cellAlign: 'left',
        prevNextButtons: true,
        pageDots: true,
        freeScroll: true,
        lazyLoad: 4
    });
});

And that's it for me. It works inside of Accordions, when they are not filled via Javascript and the content is aware all the time.

Hope I can help. Best Regards.

mohorii
  • 11
  • 2