How can I make masonry and Imagesloaded work correct. (wordpress)

Im trying to style a grid using the built in Masonry in WordPress 3.9. It works great, except that the grid fails to display correct at first pageload, but adjust on the second. I guess this is because I don’t call in ImagesLoaded, and the grid calculates before the images are loaded. This is the site: http://www.skateflix.se

To iniate Masonry I use this in Functions:

Read More
function my_masonry(){
wp_enqueue_script('masonry');
}
add_action('wp_enqueue_scripts', 'my_masonry');

I tried this to make ImagesLoaded to work but failed, placed in the header:

<script>

//set the container that Masonry will be inside of in a var
var container = document.querySelector('.js-masonry');
  //create empty var msnry
var msnry;
// initialize Masonry after all images have loaded
imagesLoaded( container, function() {
msnry = new Masonry( container, {
    itemSelector: '.feed-item'
});
});
</script>

My HTML looks like this:

<div class="js-masonry"
<div class="feed-item"
<div class="feed-item"
<div class="feed-item"
<div class="feed-item"
</div>

What am I doing wrong here? Im a bit confused. Does the version of Masonry that ships with wordpress includes ImagesLoaded, or do I have to link that in myself?

Related posts

Leave a Reply

1 comment

  1. Ok Made it work. Placed this function in a .js file (change query selector and Itemselector for your own container and the classes inside it):

    (function( $ ) {
    "use strict";
    $(function() {
    //set the container that Masonry will be inside of in a var
    var container = document.querySelector('.js-masonry');
    //create empty var msnry
    var msnry;
    // initialize Masonry after all images have loaded
    imagesLoaded( container, function() {
        msnry = new Masonry( container, {
            itemSelector: '.feed-item'
        });
    });
    });
    }(jQuery));
    

    And then enqueue it in functions.php

    wp_enqueue_script( 'masonry' );
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'masonryInit', get_stylesheet_directory_uri().'/js/masonry.js',      array( 'masonry', 'jquery' ) );