Masonry items not reloaded when cliking ajax load more button

innovation picture innovation · Mar 5, 2015 · Viewed 9.2k times · Source

Hi everyone i have one problem about masonry items.

I have created this DEMO from codepen.io

In this demo you can see there is this javascript code:

$(window).load(function()
{
$( function() {
var $container = $('.posts-holder');
    $container.masonry({
      isFitWidth: true,
      itemSelector: '.kesif-gonderi-alani'
    });

});
});

I show only 10 posts when a page is opened. If user want to show other 10 posts then user needs to click (show more button). I created this ajax function for show more posts.

$('.showmore').live("click",function(event) 
{
event.preventDefault();
var ID = $(this).attr("id");
var P_ID = $(this).attr("rel");
var URL=$.base_url+'diger_fotograflar_ajax.php';
var dataString = "lastid="+ ID+"&profile_id="+P_ID;

if(ID)
{
$.ajax({
type: "POST",
url: URL,
data: dataString, 
cache: false,
beforeSend: function(){ $("#more"+ID).html('<img src="wall_icons/ajaxloader.gif" />'); },
success: function(html){
$("div.posts-holder").append(html).each(function(){
   $('.posts-holder').masonry('reloadItems');
 });
$("#more"+ID).remove();
}
});
}
else
{
$("#more").html('The End');// no results

}

return false;
});

this code working when clicking showmore button $('.posts-holder').masonry('reloadItems'); but collecting new posts in one place. But when I change the width of the page everything is improving.

enter image description here

Answer

akmozo picture akmozo · Mar 10, 2015

I think that you can use $container.masonry(); after adding your elements, like this :

$("div.posts-holder").append(html).each(function(){
    $('.posts-holder').masonry('reloadItems');
});

$container.masonry();

You can see it working here.

Hope that can help.