Troubleshooting a recurring animation issue with animate.css in Javascript (straightforward fix)

I've encountered an issue with my Javascript code. To add animations to elements on my website, I'm using animate.css, but the animations don't work properly when repeated. Despite trying various solutions like resetting the const where the animation runs, I haven't been able to fix it. Can anyone offer some assistance? I know this should be a simple problem to solve, but for some reason, I just can't seem to pinpoint the issue. Refreshing the site is a temporary fix, but I'd prefer a more permanent solution.

Below is the code snippet used to animate the elements:

const animateCSS = (element, animation, prefix = 'animate__') =>
  // Creating and returning a Promise
  new Promise((resolve, reject) => {
    const animationName = `${prefix}${animation}`;
    const node = document.querySelector(element);

    node.classList.add(`${prefix}animated`, animationName);

    // Removing classes and resolving the Promise after animation ends
    function handleAnimationEnd(event) {
      event.stopPropagation();
      node.classList.remove(`${prefix}animated`, animationName);
      resolve('Animation ended');
    }

    node.addEventListener('animationend', handleAnimationEnd, {once: true});
  });

And here is the trigger code for animating the elements:

animateCSS('.wrapper1', 'bounceOutDown'); 

The trigger is placed on a button which initiates the animation. There's another button that triggers similar animations (Fade in and Fade out), but the issue arises when repeating these actions. You can see a demonstration of this problem at the following link:

If you're interested in reviewing the full code repository, you can find it here on GitHub. Thank you!

https://github.com/swiftybear/MarlouRentucan

Answer №1

Before animating an element, it is crucial to ensure that the element is prepared for the animation. This involves clearing any previous animation classes before adding new ones as the animationend event may not function optimally, especially with repeated animations.

Here is a solution :

// Avoid relying on the animationend listener    
node.classList.remove(`${prefix}animated`, PreviousAnimationName);
node.classList.add(`${prefix}animated`, animationName);

Alternatively :

You have the option to utilize my library, where I have implemented a function named aniUtil_flush() specifically designed to remove all animation classes.

Example usage -

aniUtil_flush("#theElement");
aniUtil_animate("#theElement", "ani_bounceInUp");

Do not be confused by the terminology utilized in the library; this is how it functions. For further details, refer to this link

Demo can be viewed here

$("#first_btn").click(function(){
  $(this).hide();
  $("#btt").show();
  aniUtil_flush("#second_btn");
  aniUtil_flush("#third_btn");
  aniUtil_flush("#forth_btn");
  aniUtil_flush("#fifth_btn");
  aniUtil_animate("#second_btn", "ani_bounceInUp");
  aniUtil_animate("#third_btn", "ani_bounceInUp");
  aniUtil_animate("#forth_btn", "ani_bounceInUp");
  aniUtil_animate("#fifth_btn", "ani_bounceInUp");
})

$("#btt").click(function(){
  $(this).hide();
  $("#first_btn").show();
  aniUtil_flush("#second_btn");
  aniUtil_flush("#third_btn");
  aniUtil_flush("#forth_btn");
  aniUtil_flush("#fifth_btn");
  aniUtil_animate("#second_btn", "ani_bounceOutDown");
  aniUtil_animate("#third_btn", "ani_bounceOutDown");
  aniUtil_animate("#forth_btn", "ani_bounceOutDown");
  aniUtil_animate("#fifth_btn", "ani_bounceOutDown");
})
.main{
  text-align: center;
  margin-top: 150px;
}

#btt{
  margin-bottom: 20px;
}
<html>
<head>
<link
    rel = "stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
  />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <script
    src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
  </script>
  <script
    src = "https://cdn.jsdelivr.net/gh/KodingKhurram/animate.css-dynamic@main/animate.min.js">
  </script>
  
</head>
  <body>
    <h2 align="center">
      Click on <strong>Button #1</strong> and <strong>Back to top</strong> to see the animations.
    </h2>
    <span class="https://stackoverflow.com/questions/73984095/javascript-animate-css-repeated-animation-problem-simple">Demo for the <a href="">stackoverflow question</a></span>
    <div class="main">
      <input type="button" id="first_btn" class="btn btn-primary" value="Button #1"/>
      <br/><br/>
      <div class="next_btn_list">
        <input type="button" id="second_btn" class="btn btn-secondary aniUtil_dramatic" value="Click me"/>
      <input type="button" id="third_btn" class="btn btn-secondary aniUtil_dramatic" value="Click me"/><br/><br/>
      <input type="button" id="forth_btn" class="btn btn-secondary aniUtil_dramatic" value="Click me"/>
      <input type="button" id="fifth_btn" class="btn btn-secondary aniUtil_dramatic" value="Click me"/>
      </div><br/>
      <input type="button" id="btt" class="btn btn-danger" value="back to top" style="display: none"/>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using both PHP $_POST and $_GET in a form submission for enhanced functionality

My preferred programming language is PHP. I am currently working on a form and once it is submitted, I want it to redirect to a specific URL with a $_POST variable attached at the end (formatted as a $_GET), for example: http://example.com/page.php?my_ke ...

The Material UI Tooltip fails to display when placed within a unique custom Modal component

Check out the way I've defined my custom Popup component: function Popup({ show, setShow, content }) { const popupRef = useRef(null); useEffect(() => { if (show) { popupRef.current.style.display = "block"; } else { popupRef. ...

Retrieving content from Angular input fields using Protractor

When using the angular Input controls, I am unable to retrieve values directly using getText() in protractor. <input ng-switch-when="TextBox" ng-if="::!field.uiControlInfo.multiLine" ng-model="field.input[0].value" ng-focus="onFieldFocus(field, 0, $eve ...

The database was successfully updated; however, the API encountered a 500 error when trying to access

Currently, I am working on a project that utilizes Javascript alongside Node.js, Express, SuperAgent, and KnexJS for database management with Sqlite3. The issue I am facing is as follows: Upon submitting data for updates through my API route using the PUT ...

Opening Tags in Selenium for HTML

Is it possible for Selenium with XPath to properly work with HTML that is not in the form of XML, and contains open tags like <col> and <input>? I'm curious if anyone can confirm this. I ask because our automation testing team has noticed ...

What Is The Process for Logging Into an ASPX Site with Jsoup?

I've been attempting to access an aspx site using a Jsoup crawler for login purposes, but all the examples I've found involve forms. However, this particular aspx website here does not seem to have any forms available. How should I proceed with t ...

The Confirm() function doesn't seem to acknowledge when I select the decline option

When the delete button is pressed, a confirm message will appear. If "Accept" is clicked, the row will be deleted from the database. However, if "Cancel" is clicked, it will still delete the row from the db. <a href="template_edit.php?delete=<?= ...

Exploring the Big O complexity of QuickSort in JavaScript

My experience with QuickSort involved testing two algorithms on LeetCode for a specific problem. Surprisingly, both algorithms worked, but one outperformed the other significantly, leaving me puzzled about the reason behind the speed difference. One of th ...

Creating a Higher Order Component in React that accepts another higher order component as a parameter

Currently, I am delving into the world of Material UI on my own and stumbled upon the HOC pattern method called withStyle HOC API. I decided to test it out by implementing a simple string style myself to grasp how this hoc (withStyle) function integrates w ...

Utilizing pop-up info boxes

After thoroughly reviewing the documentation on Imagemapster's website and browsing several posts, I am still struggling to get the tooltips working correctly. I attempted to share my HTML and JS code on jsfiddle.com without success, so I have provide ...

Transmitting intricate Javascript Array to ASP.NET Controller Function

I am facing an issue with sending a complex JavaScript array to my asp.net mvc6 controller method. I have tried two different methods to pass the data, but neither seem to be working for me. public IActionResult TakeComplexArray(IList<ComplexArrayInfo ...

What is the counterpart of Python's pip freeze in Node.js?

Is there a way to generate a list of all npm modules being used along with their versions similar to Python's pip freeze? Also, is there a command in Node.js equivalent to Python's pip install -r /path/to/requirements.txt for reproducing the envi ...

The preflight response received an unexpected HTTP status code 404 while processing an AJAX request in the browser

My ajax request is encountering a 404 error, here is the code: $.ajax({ type:'GET', url:'http://localhost:8000/auth/github', crossDomain:true, headers:{ 'Content-Type':'application/x-www-form-ur ...

The JQuery TextNTags plugin eliminates tag formatting once the trigger syntax has been modified

I have incorporated the JQuery TextNTags plugin into my web application. Here is the original code snippet: $.browser = { webkit: true }; $(function () { $('textarea.tagged_text').textntags({ triggers: {'!': { ...

Change the color of child li to white when hovering over the parent li, and vice versa

Let me start off by explaining the issue I'm facing. Take a look at to get a better understanding of what I'm referring to. It needs to be a specific page, not the home page, so you can see the problem for yourself. Now, when you hover over the ...

Continuously converting methods recursively until the array is fully processed

My current code has a method that is not very efficient and does not scale well. The object y is an array consisting of key/value pairs, each containing two properties: 1. A unique string property called name. This value is identified by the childre ...

How about blending $_GET[''] with a text?

Hey there, I'm facing an issue with the following code snippet: <?php include('pages/{$_GET["page"]}.txt'); ?> Unfortunately, it's not working as expected. The code is embedded in a functional website but it renders the div empt ...

There was a problem establishing a WebSocket connection to 'ws://127.0.0.1:2000/'. The attempt failed with the following error: net::ERR_CONNECTION_REFUSED

I have integrated websocket functionality using a repository found at https://github.com/kishor10d/CodeIgniter-Ratchet-Websocket After successfully testing the websocket on my local environment, I encountered issues when uploading the files to the live se ...

The sticky navigation bar's background fails to change at the appropriate time following an image slider

I am currently facing an issue with my sticky navigation bar. I want the background color to change to white after the user scrolls past the image slider. The problem is that the white background appears above the image slider instead of in the orange logo ...

Is there a way to prevent view re-rendering in a Route component in React using react-router-dom?

I have Objects.tsx and Property.tsx views. In Objects I created a Switch with Route to display the Property. <Switch> <Route exact path="/objects/property" component={() => ( <Property /> )} /> < ...