Skip to content
Related Articles

Related Articles

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

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 is 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 target, as a result of which the target should start translating.
  • In CSS, this transitioned 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:



HTML




<!DOCTYPE html>
<html>
  
<head>
    <!-- Styling with CSS -->
    <style>
  
        .removed{
            transform: translateX(100vw);
        }
  
        #second{
            transition: transform 1s 0s;
        }
  
        .cntnr{
            overflow-x: hidden;
        }
    </style>
</head>
  
<body>
    <section class="cntnr">
        <h2>Geeksforgeeks 1</h2>
        <h2 id="second">Geeksforgeeks 2</h2>
        <h2>Geeksforgeeks 3</h2>
        <button>Remove Second</button>
    </section>
  
    <!-- Funcitonality 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>
</body>
  
</html>

Output:

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :