Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect which CSS animation just ended in JavaScript?

How can you detect which CSS animation just finished in JavaScript?

The ultimate need is to re-trigger a CSS animation. Due to our HTML hierarchy, we prefer not checking the element's class but instead taking action only when a particular animation ends. If you have a method that allows re-triggering an animation without removing/adding a class, please let us know.

Otherwise... our code:

    page.find( '.button.letter' ).on( 'webkitAnimationEnd', function() {
        $( this ).removeClass( 'tap_animation' );

        console.log( 'Hi: ' + this.style.webkitAnimationName );

        if ( !write_mode() ) {
            do_write( this );
        }
    });

this.style.webkitAnimationName always returns the empty string.

Are we doing something wrong?

We need the code for WebKit browsers, specifically Mobile Safari.

Thanks!

like image 334
Crashalot Avatar asked Sep 19 '12 16:09

Crashalot


1 Answers

From jQuery you can access the originalEvent object, and, from there, the animationName property:

$('body').on('webkitAnimationEnd', function(e){
    var animName = e.originalEvent.animationName;
    console.log(animName);
});​

(Webkit-only) JS Fiddle demo.

From there, simply use an if to check what the animation name is/was (past-tense, I suppose, given that it ended).

The above updated, to give possibly a better illustration:

$('div').on('webkitAnimationEnd', function(e){
    var animName = e.originalEvent.animationName;
    if (animName == 'bgAnim') {
        alert('the ' + animName + ' animation has finished');
    }
});​

(Webkit-only) JS Fiddle demo.

This demo uses the following HTML:

<div><span>text</span></div>​

And CSS:

@-webkit-keyframes bgAnim {
    0%, 100% {
        color: #000;
        background-color: #f00;
    }
    50% {
        color: #fff;
        background-color: #0f0;
    }
}

@-webkit-keyframes fontSize {
    0%, 100% {
        font-size: 100%;
    }
    50% {
        font-size: 300%;
    }
}

div {
    font-weight: bold;
    -webkit-animation: bgAnim;
    -webkit-animation-duration: 2s;
    -webkit-animation-iteration-count: 2;
}

span {
    font-size: 100%;
    font-weight: bold;
    -webkit-animation: fontSize;
    -webkit-animation-duration: 4s;
    -webkit-animation-iteration-count: 1;
}
like image 112
David Thomas Avatar answered Oct 16 '22 12:10

David Thomas