-2

I had this problem almost every time when I used masonry.js on my websites. After the page was completely loaded, the images from the gallery look like this: enter image description here

In order to fix this I need to refresh the page to arrange images correctly like this: enter image description here

Any advice on how to solve this issue ?

Alin
  • 23
  • 1
  • 6
  • That’s because the image dimensions are not accessible when masonry is attempting to compute the layout. You will need to run or recalculate when the images are loaded. Share a minimal, concrete and verifiable example. Sharing screenshots without any code isn’t helpful. – Terry Apr 24 '18 at 21:08

1 Answers1

0

You use the imagesLoaded library to check if all the images are loaded before initialising your masonry grid.

Wordpress comes with imagesLoaded, you just need to enqueue it in your theme.

wp_enqueue_script( 'imagesLoaded' );

Then in your javascript you can do an if statement like so:

$('#container').imagesLoaded( function() {
  // images have loaded, initialise masonry grid.
});

The Masonry library also has a .layout method which lays out all item elements. Useful for when an item has changed size.

// jQuery
$grid.masonry('layout')
// vanilla JS
msnry.layout()

https://imagesloaded.desandro.com/

https://masonry.desandro.com/methods.html

ngearing
  • 991
  • 9
  • 17