みかづきブログ その3

本ブログは更新を終了しました。通算140万ユーザーの方に観覧頂くことができました。長い間、ありがとうございました。

👆

引越し先はこちらです!

CSSアニメーションの終了をJavaScriptで検知する

基本的にはトランジションの際はtransitionend、キーフレームアニメーションの際はanimationendをつかえばOKです。

transitionend

HTML
<div class="box"></div>
CSS
.box {
    position: absolute;
    top: 20px; left: 20px;
    border-radius: 12px;
    width: 120px; height: 120px;
    background: #E91E63;
    box-shadow: 0 0 5px rgba(0, 0, 0, .1);
    transition: left 1s ease-in-out;
}
JavaScript
(function(win, doc) {

    "use strict";

    var box = doc.querySelector(".box");
    
    box.addEventListener("transitionend", function(evt) {
        console.log(evt);
        alert("END");
    });
    
    setTimeout(function() {
        box.style.left = "200px";
    }, 0);

})(this, document);
DEMO



animationend

HTML
<div class="box"></div>
CSS
.box {
    position: absolute;
    top: 20px; left: 20px;
    border-radius: 12px;
    width: 120px; height: 120px;
    background: #E91E63;
    box-shadow: 0 0 5px rgba(0, 0, 0, .1);
    animation: moveLeft 1s ease-in-out forwards;
}

@keyframes moveLeft {
    0% {
        left: 20px;
    }
        
    100% {
        left: 200px;
    }
}
JavaScript
(function(win, doc) {

    "use strict";

    var box = doc.querySelector(".box");
    
    box.addEventListener("animationend", function(evt) {
        console.log(evt);
        alert("END");
    });

})(this, document);
DEMO


注意

  1. ベンダープレフィックスが必要なブラウザはJavaScript側のイベントにもプレフィックスが必要です。webkitであればwebkitTransitionendになります。
  2. アニメーションしている要素が途中で display: none; になると終了イベントは発火しません。
  3. transitionendイベントは変化させたプロパティの分だけ発火します。evt.propertyNameを見ると終了したプロパティがわかります。
  4. animationendイベントはanimation-iteration-countの分だけアニメーションが終了した際にのみ発火します。infiniteを指定すると発火しません。