Open In App

How to Linearly Transition the removal of a DOM element using CSS and JavaScript ?

For a particular HTML/DOM element, our job is to remove it and add a transition to the process of removal. Eventually, as soon as the trigger button is clicked, the DOM element should translate towards the right and finally be removed from sight as well as from the DOM.

Transitioning elements using CSS often confuses developers. There can be many variations for this property, practically any CSS property can be transitioned, be it opacity or position. In this tutorial, we will be transitioning the horizontal position of a text element, which will be finally be removed.



From now the DOM element to be removed will be called the target.

Approach:



Example: This example shows the use of the above-described approach.




<style>
    .removed{
        transform: translateX(100vw);
    }
      
    #second{
        transition: transform 1s 0s;
    }
      
    .cntnr{
        overflow-x: hidden;
    }
</style>
  
<section class="cntnr">
    <h2>Geeksforgeeks 1</h2>
    <h2 id="second">Geeksforgeeks 2</h2>
    <h2>Geeksforgeeks 3</h2>
    <button>Remove Second</button>
</section>
  
<!-- Functionality with JavaScript -->
<script>
    var btn = document.querySelector("button");
    var secondText = document.querySelector("#second");
      
    btn.addEventListener("click",() => {
        secondText.classList.add("removed");
    });
      
    secondText.addEventListener("transitionend",() => {
        secondText.remove();
    })
</script>

Output:


Article Tags :