DanielFox
DanielFox

Reputation: 675

Cancel 'on' event in javascript/jQuery

I have the following jQuery script in my code, that executes at the end of a CSS animation:

$('.player').on('webkitAnimationEnd', function() {
    gameOver();
});

I'd like to know how can I cancel or unset this, so that the gameOver function will not be executed anymore at the end of the animation.

Upvotes: 0

Views: 1008

Answers (1)

Chris Spittles
Chris Spittles

Reputation: 15359

Option 1: .one()

This will run once and never again until this code is bound again.

$('.player').one('webkitAnimationEnd', function() {
    gameOver();
});

http://api.jquery.com/one/


Option 2: .off()

Use off like this:

$('.player').on('webkitAnimationEnd', function() {
     gameOver();
});

function gameOver() {        
     $('.player').off('webkitAnimationEnd');
}

http://api.jquery.com/off/


Option 3

If you have multiple animation events bound to the same element, use namespacing to differentiate:

$('.player').on('webkitAnimationEnd.gameOver', function() {
        gameOver();
});

function gameOver() {        
     $('.player').off('webkitAnimationEnd.gameOver');
}

Upvotes: 4

Related Questions