desandro / masonry

:love_hotel: Cascading grid layout plugin
https://masonry.desandro.com
16.27k stars 2.11k forks source link

Add more items appended on same spot #1153

Open Depechie opened 3 years ago

Depechie commented 3 years ago

Test case: https://codepen.io/depechie/pen/xxqdJdW

When loading this code pen, you will almost never notice the problem. Somehow running it in code pen's environment will help. But occasionally you'll get the same behaviour in code pen too.

Running the attached HTML locally ( same code as the code pen ) will in fact always generate the problem. Masonry_2.html.txt

The issues is that the first add more call will position all images at the same location instead of staggering. Sub-sequential calls to the same add more function, will however work like expected.

I also captured the generated HTML during the calls, with attached develop session from Safari. You will notice that the left % are all set to 50 and the top is the same for all 3.

https://user-images.githubusercontent.com/351693/119404394-03f4c080-bce0-11eb-8297-557ba786a69d.mov

Any idea on how to handle this?

Depechie commented 3 years ago

Was able to get this fixed by using the imageloaded method.

This caught me off guard. I did use that for the first image load at page startup. But not for the additions when using the add more button. Because to official demo seems to have no need for that due to the set width and height ( https://codepen.io/desandro/pen/nhekz ).

So now I do the following when pressing the add more :

var elems = [];
var fragment = document.createDocumentFragment();
var i;
for (i = 0; i < images.length; i++) {
        var elem = getItemElement(images[i]);
        fragment.appendChild(elem);
        elems.push(elem); 
}
grid.appendChild(fragment);
var imageLoad = imagesLoaded(grid);
imageLoad.on( 'progress', function() {  msnry.layout(); });
msnry.appended(elems);

This will render the images correctly.

Is this the right procedure?