metafizzy / flickity

:leaves: Touch, responsive, flickable carousels
https://flickity.metafizzy.co
7.52k stars 605 forks source link

Initiate multiple different sliders #984

Closed alexljamin closed 4 years ago

alexljamin commented 4 years ago

Currently, I am showing two sliders with the following setup, based on the suggestion @desandro made here:

const carousels = document.querySelectorAll('.carousel');

for ( var i=0, len = carousels.length; i < len; i++ ) {
  var carousel = carousels[i];

  if(document.querySelector('.hero')){
    new Flickity( carousel, {
        autoPlay: 6000,
        pageDots: true,
        prevNextButtons: false,
        wrapAround: true
    });
  } else if (document.querySelector('.products')) {
    new Flickity( carousel, {
        autoPlay: false,
        pageDots: false,
        prevNextButtons: true,
        wrapAround: true
    });
  }
}

But for some reason, pageDots are still showing in both cases. And prevNextButtons are not showing in the second if condition. I would have thought that the loop does not go past the first condition but autoPlay setting seem to work correctly. A bit lost here and it will be great to get some feedback on what am I doing wrong. And, if possible, some pointers to the resolution.

alexljamin commented 4 years ago

As a quick fix I have added a check for flickity-enabled class presence: if(document.querySelector('.hero') && !document.querySelector('.hero.flickity-enabled')){...} Not sure if that is the best way to solve it

AdamJaggard commented 4 years ago

Your code says "if the hero exists on the page, then set up every slider this way". The else if statement is not being run. Your fix isn't really fixing the issue properly. Your if statement should check if the current carousel being set up is a child of the hero or not.

alexljamin commented 4 years ago

@AdamJaggard The else if condition resolves, because it selects the element with products class. In HTML I have class="carousel products" and the other carousel has class="carousel hero". I know this is not exactly the best way to do so and I am happy to consider your suggestions.

AdamJaggard commented 4 years ago

Post a link to codepen/jsfiddle showing a broken example, as it's hard to imagine why it would break unless you have something on the page with a class of hero.