Home > Software engineering >  How to prevent css animation to be stopped when class removed
How to prevent css animation to be stopped when class removed

Time:09-27

I have a grid. I need to highlight row with orange color on 3 seconds when I get update message from backend. When I get update, I add css class 'highlight' to my row and play my animation.

.highlight {
  animation-name: highlight;
  animation-duration: 3s;
}

@keyframes highlight {
  0% {
    background-color: orange;
  }

  99.99% {
    background-color: orange;
  }
}

For some reasons of message flow in application I need to remove highlight class before the 3 seconds ends and my animation will stop working. I expect that my animation will be playing to the end of 3 seconds.

How to make my animation play to the end even if I removed the class highlight?

CodePudding user response:

One possible way is to add a data- attribute to the element then add an animationend event listener to it so that when the animation finishes, the event listener knows to remove the class. See example below.

document.getElementById('clicky').addEventListener('click', () => {
  const element=document.querySelector('.highlight');
  element.setAttribute('data-remove-class', 'highlight');
  element.innerHTML='Will remove class at finish of animation';
});

document.querySelector('.highlight').addEventListener('animationend', (e) => {
  const removeClass = e.target.getAttribute('data-remove-class');
  if (removeClass == 'highlight') {
    e.target.classList.remove(removeClass);
    e.target.removeAttribute('data-remove-class');
    e.target.innerHTML='Class removed!';
  }
});
.highlight {
  animation-name: highlight;
  animation-duration: 3s;
}

@keyframes highlight {
  0% {
    background-color: yellow;
  }
  99.99% {
    background-color: orange;
  }
}
<div class='highlight'>Animating!</div>
<button id='clicky'>Remove Class</button>

CodePudding user response:

If you take off the animation class, it will stop the animation, logically. So what you're asking is not possible with a CSS keyframe animation class. If you want to continue the animation, why not just leave it on the element? Why do you have to take it off? Can't you use an alternative, e.g. different class, attribute, etc?

  • Related