htmlcssanimate.css

How can I make an element to fadeout after pressing a button with animate.css?


<div class="animate__animated animate__fadeInUp animate__fast" role="alert">
  <strong>${alertmsg}</strong> ${msg}
  <button type="button" class="btn-close" aria-label="Close"></button>
</div>

how can I make it to fade out after pressing the close button?

if I included both animate__fadeInUp and animate__fadeOutUp class, it will just fadeout directly.


Solution

  • I feel you could just add and remove classes using normal DOM-manipulation for the desired effect, right?

    Here's an example,

    <--! First your could just add id's to both the div and button -->
    <div id="alertContainer" class="animate__animated animate__fadeInUp animate__fast" role="alert">
      <strong>${alertmsg}</strong> ${msg}
      <button type="button" id="closeButton" class="btn-close" aria-label="Close"></button>
    </div>
    
    <script>
      const alertContainer = document.getElementById('alertContainer');
      const closeButton = document.getElementById('closeButton');
    
    
      // Later in js, you could just remove the fadeIn animation and add fadeOut
      closeButton.addEventListener('click', function() {
        alertContainer.classList.remove('animate__fadeInUp');
        alertContainer.classList.add('animate__fadeOutUp');
    
        // Wait for the animation to complete before removing the alert from the DOM
        setTimeout(function() {
          alertContainer.remove();
        }, 1000);
      });
    </script>
    

    Let me know if this helps

    Cheers