metafizzy / flickity

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

After using matchMedia to update groupCells option, Index in change function does not update on window resize when #1261

Closed handiworknyc closed 1 year ago

handiworknyc commented 1 year ago

https://codepen.io/handiworknyc/pen/qByPEyw

@desandro

After resizing, groupCells is updated successfully, but the index variable in the change function is incorrect.

Steps to reproduce:

  1. Start using the flickity between 1024 and 1299px breakpoint
  2. Increase window to 1300px or higher
  3. Loop through the flickity a few times

image

var opts = {
        "wrapAround": true,
        "pageDots" : false,
        "contain" : true,
        "prevNextButtons" : false,
        "autoPlay" : false,
        "resize" : true,
        "cellAlign" : "left",
    },
  totgroups,
  $cur = document.querySelector('.count-cur'),
    $tot = document.querySelector('.count-tot'),
    $slides = document.querySelectorAll('.carousel-cell');

        if ( matchMedia('(min-width: 1300px)').matches ) {
            opts.groupCells = 4;
            totgroups = Math.ceil(($slides.length / 4));
            $tot.innerHTML = totgroups;
        }

        if ( matchMedia('(min-width: 1024px) and (max-width: 1299px)').matches ) {
            opts.groupCells = 3;
            totgroups = Math.ceil(($slides.length / 3));
            $tot.innerHTML = totgroups;
        }

        if ( matchMedia('(min-width: 600px) and (max-width: 1023px)').matches ) {
            opts.groupCells = 2;
            totgroups = Math.ceil(($slides.length / 2));
            $tot.innerHTML = totgroups;
        }

var flkty =  new Flickity('.carousel', opts);

flkty.on('change', function(index){
  $cur.innerHTML = index + 1;
});

window.addEventListener('resize', function(){
        if ( matchMedia('(min-width: 1300px)').matches ) {
            totgroups = Math.ceil(($slides.length / 4));
            $tot.innerHTML = totgroups;
        }

        // disable draggable at 1200px
        if ( matchMedia('(min-width: 1024px) and (max-width: 1299px)').matches ) {
            totgroups = Math.ceil(($slides.length / 3));
            $tot.innerHTML = totgroups;
        }

        // disable draggable at 1200px
        if ( matchMedia('(min-width: 600px) and (max-width: 1023px)').matches ) {
            totgroups = Math.ceil(($slides.length / 2));
            $tot.innerHTML = totgroups;
        }   
})
handiworknyc commented 1 year ago

Nevermind. I needed to apply the matchMedia paramaters on window resize as well and re-init the carousel