I would like to implement an HTML5 animation that involves a bit more than just moving an item from point A to point B. That's why I am considering using keyframes rather than transitions. However, I just want the animation to run once, and only when triggered.
The problem is twofold: 1) When the animation is finished, the item returns to its start position. Is there a way to make it stay at the end position until further notice? 2) Is there a way to restart the animation later from Javascript?
The other possible solution I see would be to chain a few transitions using the onTransitionEnd event.
What is the best solution here considering performance? I am only targeting Webkit browsers, including mobile.
EDIT: based on the comment by @Christofer-Vilander I made a JSfiddle, which basically does what I wanted. Thanks!
HTML:
<button id="start">Start</button> <button id="reset">Reset</button>
<br/>
<div id="ball" class="ball"></div>
Javascript:
document.getElementById('start').addEventListener('click', function(e) {
document.getElementById('ball').classList.add('remove');
});
document.getElementById('reset').addEventListener('click', function(e) {
document.getElementById('ball').classList.remove('remove');
});
CSS:
.ball {
width:100px;
height:100px;
border-radius:100px;
background-color:darkred;
position:absolute;
top:100px;
left:200px;
}
@-webkit-keyframes slide {
from { top:100px; left:200px; }
to { top:100px; left:-100px; }
}
.remove {
animation: slide 1s linear;
-webkit-animation: slide 1s linear;
-webkit-animation-iteration-count: 1;
-webkit-animation-fill-mode: forwards;
}
The CSS animation-delay property has the following syntax: animation-delay: [time] | initial | inherit; As you can see, there are three possible values: time, initial, and inherit. The first option is [time], which is the number of seconds or milliseconds before the animation starts.
Add a class in the html element with Javascript, and the desired css animation ruleset for this class. Use animation-fill-mode: forwards;
for the animation to run once.
Then, remove the class from the element to re-run animation onClick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With