Search code examples
javascriptjqueryjquery-isotopeimagesloaded

imagesLoaded with multiple Isotope containers issue


I have multiple isotope containers in one page. Im able to load new items with ajax into each container but when I try to reLayout the items after images are loaded by using imagesLoaded plugin it only works on the last container.

My code is the following once I get the items by ajax I do:

//Get all the items                     
var $new_items = $($items).filter('.post-grid-item'),
    slugs = {};

// check items and save slugs (containers ids)
$new_items.each(function(){
    var sl =$(this).attr('data-slug');
    slugs[sl] = '';
});
// loop for each unique id                
for (var new_slug in slugs) {

    // I insert the items into the isotope container    
    $('.posts-grid.'+new_slug).isotope('insert', $new_items.filter('[data-slug='+ new_slug +']') );
    // I attached imagesloaded event to container to relayout once images are loaded
    $('.posts-grid.'+new_slug).imagesLoaded( function() {                       
            // Only runs on last container id  - why?¿?¿
            $('.posts-grid.'+new_slug).isotope('reLayout');
            $('.posts-grid.'+new_slug).isotope('reloadItems');

    });                         

}

It seems that imagesLoaded only get hooked into last container, not sure why. I don't have a live link to share, sorry


Solution

  • Once more , after writing down the problem Im facing in Stackoverflow, and looking it with a different perspective I was able to find a solution.

    Instead of calling multiple images loaded instances, I will call it just once after all images of all isotopes container are loaded. Basically I moved things around like:

                    //Get all the items 
                    var $new_items = $($items).filter('.post-grid-item'),
                        slugs = {};
                    // check items and save slugs (containers ids)
                    $new_items.each(function(){
                        var sl =$(this).attr('data-slug');
                       slugs[sl] = '';
                    });
    
                    // loop for each unique id 
                    for (var new_slug in slugs) {
                        // I insert the items into the isotope container            
                        $('.posts-grid.'+new_slug).isotope('insert', $new_items.filter('[data-slug='+ new_slug +']') );
    
                    }
                    // All images in all isotopes containers are loaded
                    $('.container.section-content').imagesLoaded( function() {                      
                        //loop again in container and relayout
                        for (var new_slug in slugs) {
                            $('.posts-grid.'+new_slug).isotope('reLayout');
                            $('.posts-grid.'+new_slug).isotope('reloadItems');
                        }   
    
                    });