简体   繁体   中英

How can I get a JavaScript CSS animation to run more than one time?

I have some JavaScript code that runs a CSS animation. It works fine, but I need to refresh the browser to get it to run again. How can I modify my code to get it to run every time the button is clicked?

Below is the code I used.

JavaScript

document.getElementById('LogoContainer').addEventListener('click',function() {
    var c = document.getElementsByClassName('logo-rec');
    for (var i = 0; i < c.length; i++) {
        c[i].classList.add('logo-animate');
    }
})

HTML

<button id="LogoContainer">
    <div class="logo-rec"></div>
</button>

CSS

.logo-animate {
    animation-name: MoveLeft;
    animation-duration: 3s;
}

@keyframes MoveLeft {
      0% { transform: translatex(0px)   }
     50% { transform: translatex(-15px) }
    100% { transform: translatex(35px)  }
}

The problem is that once the animation has run the system thinks - well I've run it, so it doesn't get run again when you click (the animation name stays the same).

So, this snippet adds an event listener for the animationend event and when that happens it removes the class setting that caused the animation so when you come to click again it's a new class setting and the animation happens once more.

 document.getElementById('LogoContainer').addEventListener('click', function() { var c = document.getElementsByClassName('logo-rec'); for (var i = 0; i < c.length; i++) { c[i].classList.add('logo-animate'); c[i].addEventListener('animationend', function() { this.classList.remove('logo-animate'); }); } })
 .logo-animate { animation-name: MoveLeft; animation-duration: 3s; } @keyframes MoveLeft { 0% { transform: translatex(0px) } 50% { transform: translatex(-15px) } 100% { transform: translatex(35px) } }
 <button id="LogoContainer"> <div class="logo-rec">abcd</div> </button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM