Skip to content
Related Articles

Related Articles

How to fade the removal of a DOM Element using CSS and JavaScript ?
  • Last Updated : 14 Sep, 2020

CSS has a vast domain, while basic CSS is essentially copy-paste, 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 on the click of a button.

HTML Code: Three text elements and a remove button are wrapped by a container.

HTML




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

CSS: The paragraph is assigned a transition for opacity with a duration of one second. Also, the “removed” class which is to be added to the removed element specifies the final “opacity” to be zero. This gives a faded look to the removal.

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

JavaScript: First, we create the DOM object of the button and paragraph (with suitable tag and id). Further, we add the event listener to the button, this listener adds a “removed” class to the paragraph which reduces the opacity and initiates the fading process. Finally, we add a listener to the paragraph which listens for the end of transition. As soon as transition completes the paragraph is removed.



Javascript




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

Final Code: The following example shows the combination of all the above codes.




<!DOCTYPE html>
<html>
<style>
    #parId {
        transition: opacity 1s;
    }
  
    .removed {
        opacity: 0;
    }
</style>
  
<body>
    <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>
    <script>
        var btn = document.querySelector("button");
        var par = document.querySelector("#parId");
        btn.addEventListener("click", e => {
            par.classList.add("removed");
        });
        par.addEventListener("transitionend", () => {
            par.remove();
        })
    </script>
</body>
  
</html>

Output:

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :