Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group cells behavior - flickity

I have a flickity carousel, and I want to enable autoPlay. When the carousel is on autoplay, I want to group the cells via groupCells: true. So far so good. When the user clicks on the previous or next buttons, I want the slider to move only 1 cell, so when the user clicks, the groupCells should be false.

My Options:

pageDots: false,
imagesLoaded: true, 
autoPlay: true, 
pauseAutoPlayOnHover: false,
wrapAround: true, 
groupCells: true,
selectedAttraction: 0.01
like image 548
balintpekker Avatar asked Sep 25 '17 08:09

balintpekker


1 Answers

Here is my solution, it's a bit hacky but seems to work, can be tested here: https://codepen.io/anon/pen/QqajpX

<div class="carousel">
  <div class="carousel-cell"></div>
  <div class="carousel-cell"></div>
  <div class="carousel-cell"></div>
  <div class="carousel-cell"></div>
  <div class="carousel-cell"></div>
  <div class="carousel-cell"></div>
  <div class="carousel-cell"></div>
  <div class="carousel-cell"></div>
  <div class="carousel-cell"></div>
  <div class="carousel-cell"></div>
  <div class="carousel-cell"></div>
</div>
<script>
    var carousel = $('.carousel').flickity({
        groupCells: true,
        autoPlay: true
    }).on( 'dragEnd.flickity', function( event, pointer ) {
        exitGroupCells();
    }).on( 'staticClick.flickity', function( event, pointer, cellElement, cellIndex ) {
        restartCarousel(cellIndex);
    });

    var flkty = carousel.data('flickity');

    flkty.prevButton.on( 'tap', function() {
      exitGroupCells(true);
    });

    flkty.nextButton.on( 'tap', function() {
      exitGroupCells();
    });

    function exitGroupCells(prev=false) {            
        if (!flkty.options.autoPlay && !flkty.options.groupCells) {
            return;
        }

        var nextCellIndex = 0;

        if (prev === true) {
            for (var i=0; i <= flkty.selectedIndex; i++) {
                nextCellIndex += flkty.slides[i].cells.length;
            }
            nextCellIndex -= 1;
        } else {
            var nextCell = flkty.slides[flkty.selectedIndex].cells[0];

            for(var i=0; i < flkty.cells.length; i++) {
                if (nextCell === flkty.cells[i]) {
                  nextCellIndex = i;
                  break;
                }
            }
        }

        restartCarousel(nextCellIndex);
    }

    function restartCarousel(nextCellIndex) {
      $('.carousel').flickity('destroy')

        $('.carousel').flickity({
            groupCells: false,
            autoPlay: false,
            initialIndex: nextCellIndex
        });
    }
</script>
like image 53
Isma Avatar answered Nov 11 '22 17:11

Isma