How to remove a div with fade out effect in JavaScript?

There are two ways you can achieve this: CSS3 animation or jQuery animation.

CSS3 Animation

  1. In your CSS document, add:

    .list {
        opacity: 1;
        -webkit-transition: opacity 1000ms linear;
        transition: opacity 1000ms linear;
    }
    
    • This will make any change of opacity to your item fade by 1000ms.
  2. Change line 4 of your JavaScript to:

    removeTarget.style.opacity = '0';
    setTimeout(() => removeTarget.remove(), 1000);
    
    • This will make your item change opacity to 0, thus making the transition from step 1 have an effect. Then it will remove the item with your code after 1000ms.

Note: Make sure the time of the CSS3 transition and the setTimeout are the same.

jQuery Animation

  1. Get jQuery

    • Go to the jQuery Website and download it, or
    • Add ` in your HTML document before any jQuery code.
  2. Change line 4 of your Javascript to:

    removeTarget.fadeOut(1000)
    
    • This will Fade Out your item by 1000ms, you can change this time to whatever you want.

In 2020 you can forgo use of use setTimeout for the animationend event, removing the need to maintain the duration in two places:

.fade-out {
  animation: fade 2s;
  -webkit-animation: fade 2s;
  -moz-animation: fade 2s;
}

/* Animate opacity */
@keyframes fade {
  from { opacity: 1 }
  to { opacity: 0 }
}
@-moz-keyframes fade {
  from { opacity: 1 }
  to { opacity: 0 }
}
@-webkit-keyframes fade {
  from { opacity: 1 }
  to { opacity: 0 }
}

const elementToFade = document.getElementById('my-element');

elementToFade.onanimationend = (e) => {
  if (e.target.classList.contains('fade-out')) {
    elementToFade.parentNode.removeChild(elementToFade);
  }
};

// To fade away:
elementToFade.classList.add('fade-out');

I've made this function a while ago for a personal project:

function removeFadeOut( el, speed ) {
    var seconds = speed/1000;
    el.style.transition = "opacity "+seconds+"s ease";

    el.style.opacity = 0;
    setTimeout(function() {
        el.parentNode.removeChild(el);
    }, speed);
}

removeFadeOut(document.getElementById('test'), 2000);