userden
userden

Reputation: 1693

How to reload jQuery Masonry, when deleting items with AJAX?

UPDATE:

Here is my CSS:

 #masonry-container {
   margin: 0 auto;
}

.box {
   width: 50%;
   margin-top: 30px;
}

I'm using Rails 4, Bootstrap and the Masonry-Rails gem. I have the following code working for jQuery Masonry to arrange my divs, in assets/javascipts/application.js:

$(function(){
  $('#masonry-container').masonry({
    itemSelector: '.box',
    isFitWidth: true
  });
});

var masonryUpdate = function() {
    setTimeout(function() {
        $('#masonry-container').masonry();
    }, 200);
}

$(document).on('click', masonryUpdate);
$(document).ajaxComplete(masonryUpdate);

It works otherwise, but when I try to delete an item with AJAX, Masonry doesn't update. Here is my view/projects/destroy.js:

$('.deleting').bind('ajax:success', function() {  
    $(this).closest('.poista').fadeOut();
});

How could I force Masonry to reload, after the code example above? For some reason .ajaxComplete(masonryUpdate) is not triggered?

It reloads if I do a page refresh, but that takes away the point of using AJAX with the destroy action...

So to explain this further, first my site looks like this:

two columns of divs

But when I delete a div, Masonry doesn't reload; it ends up looking like this, with an empty space on where the div used to be:

empty space where the div used to be

How could I reload Masonry after the AJAX destroy action?

Upvotes: 0

Views: 2762

Answers (3)

void
void

Reputation: 36703

$('.deleting').bind('ajax:success', function() {  
    $ele = $(this).closest('.poista');
    $ele.fadeOut(200, function(){
          $("#masonry-container").masonry( 'remove', $ele ).masonry();
    });

});

Upvotes: 1

DWB
DWB

Reputation: 1554

Edit

I was looking through another question of yours and I think I came up with a better solution. Your problem may actually be with the line below.

$(document).ajaxComplete(masonryUpdate);

As ajaxComplete calls a set handler function with specific arguments show here Your best bet would be to use an anonymous function to call masonryUpdate.

$(document).ajaxComplete(function(event, xhr, settings) {
  masonryUpdate();
};

This means you won't have to have a $('.deleting').bind function to handle deletes.

Old

You can actually just call masonry after you have faded an item out

$('.deleting').bind('ajax:success', function() {  
  $(this).closest('.poista').fadeOut();
  $('#masonry-container').masonry();
});

Upvotes: 0

RaduN
RaduN

Reputation: 1

you don't have to destroy the Masonry just reinitialize it after the ajax action and reload items using:

$container.masonry('reloadItems');

Upvotes: 0

Related Questions