How to Delete an Element in JavaScript After a Fade Out?

Estimated read time 2 min read

To delete an element in JavaScript after a fade-out animation is complete, you can use a combination of the setTimeout() method and the remove() method.

Here’s an example code snippet that demonstrates how to fade out an element using CSS and then remove it from the DOM using JavaScript:

<!-- HTML code for the element to be faded out -->
<div id="myElement">Element to be faded out</div>
/* CSS code for the fade-out animation */
#myElement {
  opacity: 1;
  transition: opacity 1s ease-in-out;

#myElement.fade-out {
  opacity: 0;
// Select the element you want to fade out and delete
const element = document.getElementById('myElement');

// Add a click event listener to the element
element.addEventListener('click', function() {
  // Add the "fade-out" class to trigger the CSS animation

  // Wait for the animation to complete
  setTimeout(function() {
    // Remove the element from the DOM
  }, 1000); // 1000ms = 1 second (duration of the animation)

In this example, we first select the element with the ID “myElement”. Then, we add a click event listener to this element using the addEventListener method.

Inside the event listener function, we add the “fade-out” class to the element using the classList.add() method. This triggers the CSS animation, which fades the element out over a duration of 1 second.

We then use the setTimeout() method to wait for 1 second (the duration of the animation) before removing the element from the DOM using the remove() method.

Note that the duration of the animation in the CSS code (1s) must match the duration in the setTimeout() method (1000). This ensures that the element is not removed from the DOM before the animation is complete.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply