desandro / masonry

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

Refresh masonry container after a dynamic HTML change by ajax incoming. #1135

Closed julioflima closed 4 years ago

julioflima commented 4 years ago

The @desandro gived a solution for someting that I was trying to found. But don't worked because in his example the html wasn't changed. So follow below my contribuition and I'm offering to contribute here implementing an Wiki.

Interesting use-case 🍌! In order to "refresh the content" two things need to happen:

The item has to be removed from the Masonry instance
layout
To remove an item from Masonry instance, we can use the ignore method. (This method is undocumented, but it works for us). ignore remove the item from the items that get laid out, but we can unignore that item to bring it back.

I put together an example which demonstrates dropping elements from Masonry instance, into droppable area, and back into the Masonry.

http://codepen.io/desandro/pen/btHyq

First you have to initialize the Masonry.

After ajax has coming and changed the HTML.

$('.grid').masonry({
    itemSelector: '.grid',
    columnWidth: '.grid-sizer',
    percentPosition: true,
    resize: true
});

$(".grid-item").toArray().forEach((elem)=>{
        $('.grid').masonry('ignore', elem).masonry();
        $('.grid').masonry()
          .append( elem )
          .masonry( 'appended', elem )
          .masonry();
})

2 days on this, should be newbie, but I'cant leave the "discovery" just for me. Wasn't something that @desandro don't implemented, in the contrary, but was't much documented or related on web. So is it.