Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a CSS3 keyframe animation once, and only when triggered?

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;
}
like image 987
Per Quested Aronsson Avatar asked Oct 25 '13 08:10

Per Quested Aronsson


People also ask

How do I delay an animation in CSS?

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.


1 Answers

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.

like image 107
katsampu Avatar answered Sep 29 '22 16:09

katsampu