Thursday, 3 February 2022

How to keep the reached state of an animate.css animation?

I have an element which is invisible at first (opacity: 0).
When an animation is triggered, it fades in, but since the value of opacity seems to get reset, it vanishes again after completion.

How do I prevent a reset of the animated properties?



Example context:

HTML:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />

<div class="main-container">
  <div id="test1"></div>
</div>

CSS:

#test1 {
  position: absolute;
  
  margin: 10%;
  
  width: 25%;
  height: 25%;
  
  opacity: 0;
  
  background: blue;
}

The code below uses this JS function to add animation classes (found on the animate.css website):

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

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

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

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


Here I try to trigger an in animation, wait for a moment and then have an out animation.
The described problem manifests as a flickering (can be seen in this jsfiddle.)

  • First I thought that the solution should be as easy as changing the property.

    after completion:

    let test1 = document.getElementById("test1");
    
    animateCSS("#test1", "flipInX")        // flickers
        .then(()=>{
            test1.style.opacity = 1;
        });
    
    ...
    
    animateCSS("#test1", "flipOutX")
        .then(()=>{
            test1.style.opacity = 0;
        });
    

    immediately:

    let test1 = document.getElementById("test1");
    
    
    animateCSS("#test1", "flipInX")
    test1.style.opacity = 1;
    
    ...
    
    animateCSS("#test1", "flipOutX")       // flickers
    test1.style.opacity = 0;
    

  • Then I thought that the flickering is caused by any animation delay.
    So I disabled that:

    test1.style.setProperty('--animate-delay', '0s');`
    document.documentElement.style.setProperty('--animate-delay', '0s');
    

    Without any effect.


What am I doing wrong?



I use animate.css 4.1.1 with Google Chrome.



from How to keep the reached state of an animate.css animation?

No comments:

Post a Comment