jquery help - initialize Masonry after all images have loaded

Peter Eastwood picture Peter Eastwood · Aug 13, 2015 · Viewed 10.1k times · Source

I am using a masonry plugin but my images are overlapping when the page first loads. If I change the width of the browser they fall into place. The developer told me to do the following but I am unsure how to "add it: to my custom.js file properly.

I was just told to:

// with jQuery
var $container = $(’#container’);

// initialize Masonry after all images have loaded
$container.imagesLoaded(function(){
    $container.masonry();
});

Can anyone properly format this advice so I can use it?

Answer

Bram Vanroy picture Bram Vanroy · Aug 13, 2015

He wants you to use the imagesLoaded plugin.

Load that plugin

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/3.1.8/imagesloaded.pkgd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/3.3.1/masonry.pkgd.min.js"></script>

and use as follows:

$(document).ready(function () {
    var $container = $("#container");

    $container.imagesLoaded(function () {
        $container.masonry();
    });
});

What this does is:

  1. Wait for the document to be ready
  2. Wait for the images inside the container to have loaded
  3. Run masonry on the container