sukesh
sukesh

Reputation: 2437

How to apply masonry to items appended by ajax call

I have a picture grid and in the Mobile View (320 X 480), there is a "Load More" button. The container div is as follows:

<div id="divMoments" class="grid" data-masonry='{ "itemSelector": ".grid-item"}'>
  <div class="grid-item">
     <div class="gridContainer">
       <img src="ImageURL" />
       <p>OwnerName</p>
     </div>               
  </div>
</div>

On the button click, it triggers an ajax call. The received result is a html string of many such grid items:

"<div class=\"grid-item\">imagex<div>
 <div class=\"grid-item\">imagey<div>
..."

After appending the string to the container, I have the jQuery code to reload masonry, but all the images are overlapped. When I check the html, the masonry css is applied to all the items.

function GetNextSet() {
            jQuery.ajax({
                url: "/api/sitecore/Moment/GetNextSet",
                type: "POST",
                context: this,
                success: function (data) {
                    ShowNextResultSet(data);
                }
            });
        }

function ShowNextResultSet(data) {
  var $content = jQuery(data.ResultSet);
  jQuery("#divMoments").append($content).masonry('appended', $content);
  jQuery("#divMoments").masonry('reloadItems');
  jQuery("#divMoments").masonry();
}

using masonry v4.1.1

enter image description here

Upvotes: 1

Views: 1039

Answers (1)

sukesh
sukesh

Reputation: 2437

Re-applying masonry after a delay worked for me.

function ShowNextResultSet(data) {
  var $content = jQuery(data.ResultSet);
  jQuery("#divMoments").append($content).masonry('appended', $content);

  setTimeout(function () {
     jQuery("#divMoments").masonry('reloadItems');
     jQuery("#divMoments").masonry();
  }, 100);
}

Upvotes: 2

Related Questions