Freeman
Freeman

Reputation: 39

Refresh jquery.masonry when deleting an item

How do I refresh Masonry when an item is deleted via Ajax? This is the code I'm using to delete the item:

if($deletes = $('a[rel=delete]')) {
    $deletes.click(function() {
        if(!window.confirm('Are you sure you wish to delete this picture?'))
            return false;
        $t = $(this);
        $.post(
            $t.attr('href'),
            {},
            function(data) {
                if(data == "success")
                    $t.parents('.deleteable:first').fadeOut();
            }
        );
        return false;           
    });
}

The reason I want a refresh is to eliminate the resulting spaces after items are deleted.

Upvotes: 4

Views: 12746

Answers (4)

mountriv99
mountriv99

Reputation: 918

jquery masonry itself has a remove method (http://masonry.desandro.com/methods.html#remove)

you can put this in your fadeOut callback:

$("your-container").masonry( 'remove', $(this) ).masonry();

Upvotes: 1

Sandwich
Sandwich

Reputation: 2289

Call masonry again in fadeout callback. Make this easy on yourself, and do your masonry initialization in a function. Define your options in there so that you don't have to carry the options into your callback scope.

Like so

$(function(){

  var $bricks = $('your > elements');

  function BuildWall(){
    $bricks.masonry({your:'options'});
  }

  BuildWall();


 //Your code modified
 if($deletes = $('a[rel=delete]')) {
     $deletes.click(function() {
        if(!window.confirm('Are you sure you wish to delete this picture?'))
           return false;
         var $t = $(this);
         $.post(
            $t.attr('href'),
            {},
            function(data) {
                if(data == "success")
                    $t.parents('.deleteable:first').fadeOut(function(){
                       //This is faster than $(this).remove();
                       $(this).empty().remove();
                       //Reset Masonry
                       BuildWall();
                    });
            }
        );
        return false;           
    });
 }
});

Upvotes: 1

John Flatness
John Flatness

Reputation: 33789

Add a callback to your fadeOut() to actually call .remove() your deleted element once it's faded out, then just call .masonry() on the container again.

Upvotes: 5

Brad Christie
Brad Christie

Reputation: 101614

I would say just call it again on the selector. It seems to have a check to see if it's been called again.

...snip...
  // checks if masonry has been called before on this object
  props.masoned = !!$wall.data('masonry');
...snip...

I also would recommend the saveOptions setting, since it seems to support it for re-calls. Never mind, it seems to do so by default (D'oh!)

Upvotes: 1

Related Questions