4

Is there a way to restart a CSS animation without cloning elements, reflowing DOM, waiting (setTimeout/onAnimationEnd)?

3
  • @freedomn-m of course not, see the word "like"
    – Luca Rossi
    Nov 2, 2017 at 11:42
  • @freedomn-m not really, since it can be used in every actual "restarting animation" scenarios
    – Luca Rossi
    Nov 2, 2017 at 11:46
  • What's the case where a setTimeout is undesirable?
    – Matthew
    Mar 5, 2020 at 14:33

1 Answer 1

11

EDIT: No jQuery or check needed.

I basically just restart the animation at the next painted frame.

This method doesn't clone any element, reflows the document, setting any timeout, or waiting for completion of the animation. It is 100% flexible and requires no jQuery.

I haven't seen anything similar (not even at css-tricks) so I wanted to share my idea with you and hear your thoughts.

Browser support

document.querySelector('.box').onclick = function(){
  requestAnimation( this );
};

var requestAnimation = function( obj ){
  obj.style.animation = 'none';
  window.requestAnimationFrame(function(){
    obj.style.animation = 'myAnimation 1s';
  });
}
html{ background: #212121; }

.box{
  width: 150px;
  background: white;
  cursor: pointer;
  text-align: center;
  margin: auto;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 3px black;
}
span{
  float: right;
  color: grey;
}
@keyframes myAnimation{
  from{ background: grey; transform: scale(1.2); }
  to{ background: white; transform: scale(1); }
}
<div class="box">I can animate forever!</div>
<span>By Luca Rossi</span>

5
  • can you post the same function in pure javascript
    – vikrant
    Nov 2, 2017 at 17:05
  • @vikrant pure javascript, no check for state needed!
    – Luca Rossi
    Nov 2, 2017 at 18:46
  • I will try to use this method in my project
    – zzzgoo
    Feb 23, 2019 at 3:09
  • I will observe whether there will be some disadvantages.
    – zzzgoo
    Feb 23, 2019 at 3:43
  • Works great on PC. Not so much on Android Vivaldi
    – DAG
    Sep 16, 2021 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.