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

13,774

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.

Share:
13,774
Per Quested Aronsson
Author by

Per Quested Aronsson

SOreadytohelp Javascript frontend mobile, CTV and video domain specialist, also familiar with server-side technologies, including Node, PHP, PostgreSQL, MySQL, AWS, etc. I have advanced skills in Javascript, SQL, data analysis, data presentation, and HTML5/CSS3.

Updated on July 20, 2022

Comments

  • Per Quested Aronsson
    Per Quested Aronsson almost 2 years

    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;
    }