Is there a way to restart a CSS animation without cloning elements, reflowing DOM, waiting (setTimeout/onAnimationEnd)?
1 Answer
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.
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>
setTimeout
is undesirable?