user1072337
user1072337

Reputation: 12945

Using .hide with .remove function in JQuery does not remove item from the DOM

I am trying to remove an element with JQuery, but I would still like the transition of the .hide function. I came up with this solution:

$("#box-"+likeid).hide('slow', function(){ $("#box-"+likeid).remove(); });

However, after this, I want to iterate over a list of items where index matters (I use .each). All of these items have the same class, so I iterate over the items with that class and find index from that.

I'm discovering that, when I use the above hide/remove solution, the item is still being counted as an item with an index. However, when I just use plain .remove, it is not counted and it behaves how I wanted.

But back to the earlier point, I like the .hide transition. Is there a way around this? Thank you.

EDIT:

This is the full Jquery function:

$(".remove-item").click(function(event) {

      event.preventDefault();

      var id = $(this).find("i.fa-times").attr('id');

      var likeid = id.replace( /^\D+/g, '');

      var elem = $("#box-"+likeid).hide('slow', function() { $("#box-"+likeid).remove(); });

      $('.spacer').remove();

      $('.boxBg').not(elem).each(function() {
              $(this).removeClass('last');

              if (($(this).index() + 1) % 4 == 0){

                $(this).addClass('last');
                $('<div class="spacer"></div>').insertAfter($(this));
              }


      });

});

Basically, I want every fourth element to have the class "last" that signifies a new row. When one is deleted, I want to update this. However, when using this, it is not assigning last to the correct ones. It is one off, even when using this way of doing it that you shared below.

Upvotes: 1

Views: 87

Answers (1)

Ram
Ram

Reputation: 144689

That's because the callback function is executed 600ms (slow) later, you can either move the each loop into the callback or exclude the element from the collection using the not method:

// `hide` returns the current collection
var $elem = $("#box-"+likeid).hide('slow', function(){ $(this).remove(); });

$collection.not($elem).each(function(i) {
    // ...
});

Upvotes: 1

Related Questions