Masonry layout galleries with Macy.js

As explained in the tutorial How to add a real masonry layout in easy posts element, the masonry layout in Oxygen is not a real masonry.

It's made with Flexbox , that's why it looks like that:

instead of that:

Which is fine in some case but sometimes, the order is important (if we want the first images to be at the top of the page).

So this time, instead of using the masonry javascript library, we are going to use Macy.js

The reason : it's super light and easier to use.

Step 1

Go to this page to download the ZIP file: https://github.com/bigbite/macy.js Upload and enqueue the JS file :

wp_enqueue_script( 'macy-js', plugin_dir_url( __FILE__ ) . 'assets/js/macy.js', '', '', true );

[ see HOWTO to learn how to add custom files ]

Step 2

Create a new gallery and choose masonry as Layout:

Here is the default gallery created:

Step 3

Let's add a class to this gallery and call it .freakgallery

Then add an Overflow:hidden or you might see a scrollbar at the right border sometimes:

Step 4

Add a Code Block and paste this Javascript code:

var macy = Macy({
    container: '.freakgallery',
    trueOrder: false,
    waitForImages: false,
    margin: 10,
    columns: 4,
    breakAt: {
        1120: 3,
        992: 3,
        768: 2,
        480: 1
    }
});

And that's it for the basic options.

As you can see in the code, we can control the margin (gap between images), the number of columns, and the number of columns based on the width of the viewport.

Here is how it looks now:

The fun part

Here is a little tip that I like to use.

I create a new Div (100% width) with the title of the gallery or whatever:

GALLERY TITLE

Then with some JS code, I move the Div to the gallery so it became an element of this gallery:

$(".gallerytitle").prependTo(".freakgallery");

Resize the window to see the result.

GALLERY TITLE

You might see the Div 'moving' from his original position to the gallery, as it will be visible before all the photos are loaded. Which doesn't look great.

So I create a new class called .hide , with a display:none, then I add this code:


(function($) {
    $(".gallerytitle").prependTo(".freakgallery");

    var macy = Macy({
        container: '.freakgallery',
        trueOrder: false,
        waitForImages: true,
        margin: 10,
        columns: 4,
        breakAt: {
            1120: 3,
            992: 3,
            768: 2,
            480: 1
        }
    });

    macy.runOnImageLoad(function() {
        macy.recalculate(true, true);
        $(".gallerytitle").removeClass("hide");
        $(".freakgallery").removeClass("hide");
    });

})(jQuery);

Basically, the Div and the gallery will be hidden until all the images are loaded. Then Macy will do his magic and we will remove the .hide class at the same time.

Don't forget to check the Macy.js page, there are some other sweet options.