Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reinit flickity after page update by ajax call

I'm giving flickity by metafizzy a try. Working great but after updating the page the newly loaded gallery won't function. How can I reinitialize flickity after ajax load? I use the js-flickity class to initialize the script.

<div class="gallery js-flickity">
...
</div>
like image 919
waterschaats Avatar asked Jul 01 '15 14:07

waterschaats


1 Answers

I know it's a bit too late, but I'll post it anyway as it might help someone else.

Haven't tried the resize solution submitted above, but this is how I did it.

After you append your elements to your container, look for the js-flickity elements, see if you can get the object data using data method, and if it's undefined initialise flickity on that element.

var nodeList = document.querySelectorAll('.js-flickity');

for (var i = 0, t = nodeList.length; i < t; i++) {
    var flkty = Flickity.data(nodeList[i]);
    if (!flkty) {
        new Flickity(nodeList[i]);
    }
}

Update:

Noticed that there's still quite few people still looking at this question. So here's an updated solution, that also supports flickity carousel options defined in data attribute (optional).

var nodeList = document.querySelectorAll('.js-flickity');

for (var i = 0, t = nodeList.length; i < t; i++) {
    var flkty = Flickity.data(nodeList[i]);
    if (!flkty) {
        // Check if element had flickity options specified in data attribute.
        var flktyData = nodeList[i].getAttribute('data-flickity');
        if (flktyData) {
            var flktyOptions = JSON.parse(flktyData);
            new Flickity(nodeList[i], flktyOptions);
        } else {
            new Flickity(nodeList[i]);
        }
    }
}
like image 157
Ed T. Avatar answered Sep 22 '22 05:09

Ed T.