6

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?

Dan Lowe
  • 37,115
  • 15
  • 104
  • 98
Peter Eastwood
  • 215
  • 2
  • 4
  • 10
  • 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 '15 at 15:20

2 Answers2

14

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
Bram Vanroy
  • 22,919
  • 16
  • 101
  • 195
  • 2
    WOW! thanks for the great advice. Your advice seems to be working. – Peter Eastwood Aug 13 '15 at 15:23
  • maybe a bit later, but does this work with dynamically created content and graphs instead of images? – Wouter Jan 11 '17 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. – Bram Vanroy Jan 11 '17 at 12:59
  • @Bram I've made a question about it – Wouter Jan 11 '17 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();
});
LTasty
  • 1,987
  • 11
  • 20
  • difference between document ready and window load: http://stackoverflow.com/questions/5182016/what-is-the-difference-between-window-load-and-document-ready – LTasty Aug 13 '15 at 15:15
  • 1
    Window load isn't necessary as he's already using images loaded. Remove one or the other. – Bram Vanroy Aug 13 '15 at 15:17