AlwaysStudent
AlwaysStudent

Reputation: 1374

JQuery masonry doesn't work after ajax click

I have a problem with my ajax code. I created a DEMO from jsfiddle.net

In this demo you can see the grid system it is working fine. But when you click the button for load more post the problem will be come on that time.

What is the problem in my code? Anyone can help me in this regard ?

$(document).ready(function() {
function loadMore() {
    $('.posts-holder').append('<div class="kesif-gonderi-alani" style="height:300px; background:blue;">6</div>');
    $('.posts-holder').append('<div class="kesif-gonderi-alani" style="height:300px;">7</div>');
    $('.posts-holder').append('<div class="kesif-gonderi-alani" style="height:300px;">8</div>');
     $('.posts-holder').append('<div class="kesif-gonderi-alani" style="height:300px;">9</div>');
     $('.posts-holder').append('<div class="kesif-gonderi-alani" style="height:300px;">10</div>');

  }
  function ajax() {
    // fake request
    setTimeout(function(){
      loadMore();
      test();
    },1500);
  }
  $('.button').bind('click', function(e){
    e.preventDefault();
    ajax();

  });
  function test(){
  var $container = $(".posts-holder");
  $container.imagesLoaded(function() {
    $container.masonry({
      columnWidth: ".kesif-gonderi-alani",
      itemSelector: ".kesif-gonderi-alani"
    });
  });
  }
  test();
});

Upvotes: 2

Views: 281

Answers (1)

Nico Vignola
Nico Vignola

Reputation: 479

Use the Masonry append method insted of jQuery one. I've uploaded in your fiddle the function loadMore.

function loadMore() {

  var $items = $('<div class="kesif-gonderi-alani" style="height:300px;">6</div><div class="kesif-gonderi-alani" style="height:300px;">7</div><div class="kesif-gonderi-alani" style="height:300px;">8</div><div class="kesif-gonderi-alani" style="height:300px;">9</div><div class="kesif-gonderi-alani" style="height:300px;">10</div>');

      $('.posts-holder').append($items)
      // add and lay out newly appended items
      .masonry('appended', $items);
}

The append method of Masonry need a jQuery object. So in your real ajax call you will create these new object and put them as argument in the append method.

Upvotes: 2

Related Questions