Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Three “h2” tags and a button are wrapped inside a container section. The second tag is unique with an id “section”.
  • The target is having an id (“second”) to transition the motion. This is done by using the transition attribute in CSS.
  • Add a click event listener to the button, which adds a class(“removed”) to the target, as a result of which the target should start translating.
  • In CSS, this transition for the element with id (“second”) is set to transform 1s 0s.
  • Now, set the “transform” attribute of the heading to be removed, equal to translateX(len), here len refers to the length through which the element has to be translated. We set it to “100vw”.
  • Lastly, an event listener is added to the target which listens for the Transition-End. This removes the target with the help of JavaScript’s remove() method.

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

HTML




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



Last Updated : 17 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads