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:
- HTML Code: Three text elements and a remove button are wrapped by a container.
- 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.
- JavaScript: First, we create the DOM object of the button and paragraph (with a 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 the transition. As soon as the transition completes the paragraph is removed.
Example: Below is the implementation of the above-explained approach.
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
#parId { transition: opacity 1 s; } .removed { opacity: 0 ; } |
Javascript
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.
Contact Us