Home > Software design >  Remove in animation() doesn't remove
Remove in animation() doesn't remove

Time:12-17

I have a div id'ed #scenario which has a number of <p> elements as children. I want to have a function that fades them out one by one in reverse order and then removes them from the DOM. I'm using jQuery.

My code:

function fadeAndDelete() {
  var elements = $("#scenario").children().get().reverse();
  $.each(
    elements, function(index, element) {
      element.animate(
        {'color': 'rgba(0, 0, 0, 0)'}, 1000, function() {
          $(this).remove();
        }
      );
    }
  )
};

I also tried to use element.remove() and $(element).remove(), and none of them worked.

Bonus points: in an ideal world, there would be a time-gap between the removals of the element (as if using a sleep() function inbetween the each() cycles).

CodePudding user response:

The animate() you're using is the DOM animate, not jquery's:

https://developer.mozilla.org/en-US/docs/Web/API/Element/animate

animate(keyframes, options)

There's no callback parameter for this function, so it's not that .remove() doesn't work, it's that the function is never called.

To use jquery's animate you need a jquery object:

$.each(elements, function(index, element) {
      $(element).animate(...

However, note that jquery is notorious for not being able animate colours without an additional plugin or using css, so your code will then not animate, but the .remove() will be called.


For the one-at-a-time scenario, you can use setTimeout. There's plenty of existing answers on SO for this, but here's your code:

function fadeAndDelete() {
  var elements = $("#scenario").children().get().reverse();

  $.each(elements, function(index, element) {
    setTimeout(function() { 
      $(element).fadeOut(2000, function() { 
        this.remove(); 
      }); 
    }, index*500);
  });
};

fadeAndDelete();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=scenario>
  <div>a</div>
  <div>b</div>
  <div>c</div>
</div>

CodePudding user response:

You can try the solution 2 from this link

I hope it will be useful

And maybe you could try element.style('display:none';) instead of remove ?

  • Related