Open In App

How to fade the removal of a DOM Element using CSS and JavaScript ?

In this article, we will fade the removal of a DOM Element using CSS and JavaScript.

CSS has a vast domain, while basic CSS is essentially copy-pasted, it can become highly complicated when merged with front-end technologies like JavaScript and related frameworks. Therefore it is noticed that some highly skilled back-end developers struggle to design the front-end of their portfolio websites. A lot many JavaScript attributes and properties linked with CSS are rarely used by beginners. This article makes use of one such attribute to fade and ultimately remove a paragraph at the click of a button.



Approach:

Example: Below is the implementation of the above-explained approach.






<section class="container">
  <h1 class="notRemoved">
    I am confident I will not be removed!
  </h1>
  <p id="parId">Don't remove me I beg you</p>
  <h1 class="notRemoved">
    I will also not be removed
  </h1>
  <button>Remove</button>
</section>




#parId {
  transition: opacity 1s;
}
.removed {
  opacity: 0;
}




var btn = document.querySelector("button");
var par = document.querySelector("#parId");
btn.addEventListener("click", e => {  
  par.classList.add("removed");
});
par.addEventListener("transitionend", () => 
{
  par.remove();
})

Output: Click here to check the live Output.


Article Tags :