user1873468
user1873468

Reputation: 477

CSS Animation + Javascript Callback

I have a CSS transition that uses -webkit-transform: translateX to move a div from the right to the left, its a basic sliding movement (I am guaranteed to only have webkit users in my case).

My problem is that I need to run an action when the animation completes, and up until now I have been using a setTimeout call in javascript to run 1 ms after the animation completes.

It works 99% of the time perfectly, but in rare circumstances, it doesn't go smoothly and it causes problems and I know this is due to the timeout not running exactly at the correct time.

From my research online, I have heard of adding an event listener for webkit transition end but cannot get it working, it works fine on someone else's example online:

jsfiddle.net/jfriend00/5FnwY/

My animation is triggered by javascript, on click of a button, the .move_in class is added to the main div element which then starts the animation. The CSS is below:

.renderZone {
    -webkit-animation-timing-function:ease-in-out;
    -webkit-animation-duration:805ms;
    -moz-animation-timing-function:ease-in-out;
    -moz-animation-duration:805ms;
}

.move_in {
    -webkit-transform: translateX(0%) !important;
    -webkit-animation-name: slideouttoleft;
    -moz-transform: translateX(-0%) !important;
    -moz-animation-name: slideouttoleft;
}

.move_out {
    -webkit-transform: translateX(-100%) !important;
    -webkit-animation-name: slideouttoleft;
    -moz-transform: translateX(-100%) !important;
    -moz-animation-name: slideouttoleft;
}

@-webkit-keyframes slideouttoleft {
    from {
        -webkit-transform: translateX(0);
    }
    to {
        -webkit-transform: translateX(-100%);
    }
}

Does anybody have any idea of the best way to approach this, or even a better way of doing what I am doing? I need to keep the CSS animation running the way it is as this provides the best performance on iOS which I have been experimenting a lot with.

Hoping somebody can help!

Thanks!!!

Upvotes: 0

Views: 915

Answers (1)

BingeBoy
BingeBoy

Reputation: 2981

CSS3 has a property called “webkitAnimationEnd” which can be used as an event lister in JavaScript.

Example code:

function cssAnimationEnd() {
    //looks for the ID box from the css and fires the event listen when the animation is complete.
    box.addEventListener( 'webkitAnimationEnd', function( event) {
      alert( "Finished animation!" );
    }, false );
}

Upvotes: 1

Related Questions