user4082764
user4082764

Reputation:

Masonry items not reloaded when cliking ajax load more button

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

Upvotes: 2

Views: 10810

Answers (2)

akmozo
akmozo

Reputation: 9839

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.

Upvotes: 7

naman kalkhuria
naman kalkhuria

Reputation: 404

you have to use the appended method of masonry ... otherwise how would it know that you have added any new element.

Adding the elements simply wont align them as masonry doesnt have any event listner for new element added.

  var el = $('<div class="kesif-gonderi-alani" style="height:300px;"></div>') 
  $container.masonry().append( el ).masonry( 'appended',el );  

Hers is small demo on codepen http://codepen.io/knaman2609/pen/xbJMRY

Click on the button to append elements dynamically

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

Upvotes: 1

Related Questions