Search code examples
javascripthtmlcssanimationfade

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


I want to remove a div element on click event but i want to remove it with a fade out effect. I have got some JQuery solution but i need pure JavaScript or css solution.

document.querySelector('.list').addEventListener("click", function(e){
    if (e.target.localName === "span") {
        var removeTarget = e.target.parentNode.parentNode;
        removeTarget.parentNode.removeChild(removeTarget);
    };
});

This code is removing the div element with no effect. How can i add a fade out effect?


Solution

  • 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.