7

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?

1
  • 1
    This code example contains smart quotes in the first line of code. You should make sure those are regular single or double quotes in your actual code, not smart quotes.
    – Dan Lowe
    Aug 13, 2015 at 15:20

2 Answers 2

16

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
4
  • 2
    WOW! thanks for the great advice. Your advice seems to be working. Aug 13, 2015 at 15:23
  • maybe a bit later, but does this work with dynamically created content and graphs instead of images?
    – Wouter
    Jan 11, 2017 at 12:54
  • 1
    @Wouter No, not as far as I know. I assume you use ajax for dynamically loaded content. In that case you can use the ajax complete event. Your graphs are probably created by a plug-in, it's likely that this plug-in also has an event that fires when the creation has finished. Jan 11, 2017 at 12:59
  • @Bram I've made a question about it
    – Wouter
    Jan 11, 2017 at 13:02
5

You can insert your code in $(window).load(function() and mansonry inizialize after all element are load.

Example:

$(window).load(function(){
var $container = $(’#container’);
$container.masonry();
});
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.