reinit flickity after page update by ajax call

waterschaats picture waterschaats · Jul 1, 2015 · Viewed 9.8k times · Source

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>

Answer

Ed T. picture Ed T. · Jul 8, 2016

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]);
        }
    }
}