ImagesLoaded.js won't work with Isotope and LazySizes

831 views Asked by At

I apologise if there is an answer out there, please point me towards the correct duplicate if so.

I'm trying to build a mini gallery which uses lazysizes for lazy-loading, isotope for sorting, and imagesLoaded to reflow the layout when a lazy image is loaded.

For some reason my imagesLoaded function won't update Isotope, but if I log the event and then manually run iso.layout() it DOES reflow the layout. Any ideas what's up?

import lazySizes from 'lazysizes';
const Isotope = window.Isotope = require("isotope-layout/dist/isotope.pkgd.js");
const imagesLoaded = window.imagesLoaded = require("imagesloaded/imagesloaded.pkgd.js");

//.....

document.querySelectorAll(".content-gallery .medias").forEach(element => {
    const elem = element;

    const iso = new Isotope(elem, {
        itemSelector: ".media",
        layoutMode: "fitRows",
        percentPosition: true,
    });

    function reflow(){
        iso.layout();
    }

    imagesLoaded(elem)
        .on("progress", reflow)
        .on("always", reflow)
        .on("done", reflow)
        .on("fail", reflow)
        .on("lazyloaded", reflow)
        .on("load", reflow);

});

If I do a nasty setInterval() then isotope also relflows, so it appears there's something wrong with ImagesLoaded.

1

There are 1 answers

0
Matthew Spence On BEST ANSWER

The imagesLoaded documentation is misleading, you cannot use .on in native JS to listen for events, you must use element.addEventListener().

Example:

function reflow(){
    iso.layout();
}

new imagesLoaded(elem);

elem.addEventListener("progress", reflow);
elem.addEventListener("always", reflow);
elem.addEventListener("done", reflow);
elem.addEventListener("fail", reflow);
elem.addEventListener("lazyloaded", reflow);
elem.addEventListener("load", reflow);