jquery help - initialize Masonry after all images have loaded
Asked Answered
S

2

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?

Sp answered 13/8, 2015 at 15:10 Comment(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.Viperish
C
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
Copulate answered 13/8, 2015 at 15:12 Comment(4)
WOW! thanks for the great advice. Your advice seems to be working.Sp
maybe a bit later, but does this work with dynamically created content and graphs instead of images?Grudging
@Grudging 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.Copulate
@Bram I've made a question about itGrudging
D
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();
});
Desiderate answered 13/8, 2015 at 15:13 Comment(2)
difference between document ready and window load: #5182516Desiderate
Window load isn't necessary as he's already using images loaded. Remove one or the other.Copulate

© 2022 - 2024 — McMap. All rights reserved.