Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Masonry Events: Call event after imagesLoaded and layoutComplete

So here's what I'm trying to do. I have a grid with a lot of images, so I'm using the imagesLoaded library along with masonry.

Here's my CSS:

.grid {
    opacity:0;
}

And HTML:

<div class="grid">
    <div class="grid-sizer"></div>
    <div class="gutter-sizer"></div>
    <div class="item">image</div>
    <div class="item">image</div>
    <div class="item">image</div>
</div>

And here's my JS:

var $container = $('.grid');
// initialize Masonry after all images have loaded  
$container.imagesLoaded( function() {
    $container.masonry({
        columnWidth: '.grid-sizer',
        itemSelector: '.item',
        gutter: '.gutter-sizer'
    });
    $container.masonry('on', 'layoutComplete', function(){
        console.log('got here');
        $container.animate({'opacity':1});
    });
});

My goal is to have the grid hidden until all images are load and the layout is complete, and then fade it in. For some reason in my code above, it's never getting into the on layoutComplete block.

If I move that block outside of imagesLoaded, $container.masonry is undefined that point.

Any ideas?

FIDDLE HERE

If you change the grid opacity to 1 you can see everything is getting laid out fine. Just trying to figure out how to get the layoutComplete to call to set the opacity to 1.

like image 380
Corey Avatar asked Feb 06 '15 17:02

Corey


1 Answers

You don't need to use the layoutComplete event on masonry. As you can just add your animation code under the masonry initialization .

When all images are loaded, the imageLoaded function will execute. You can then create the masonry object and animate right away like so:

var $grid = $('.grid').imagesLoaded( function() {
// init Masonry after all images have loaded
$grid.masonry({
  columnWidth: 200,
  itemSelector: '.item',
  gutter: 10
});
console.log('got here');
    $('.grid').animate({'opacity':1});
});

Here is a jsfiddle that demonstrate that

like image 94
muchwow Avatar answered Sep 19 '22 17:09

muchwow