Bind CSS animation events to user end using jQuery or JavaScript?

We have several animations against the same object. We must take various actions when each of these animations ends.

Right now, we are attached to the webkitAnimationEnd event and use gnarly if / then statement to handle each animation differently.

Is there a way to create custom webkitAnimationEnd events, allowing us to fire a special event handler when a particular animation finishes? For example, handler 1 handler1 and handler < > . .

We create Webkit browsers, in particular Mobile Safari.

Thanks!

+6
source share
1 answer

For a simple event trigger, you can pass a function to the jQuery trigger() method and use the return value of this function to trigger a specific event trigger (which you can then listen to:

 function animEndTrigger(e) { if (!e) { return false; } else { var animName = e.originalEvent.animationName; return animName + 'FunctionTrigger'; } } $('body').on('bgAnimFunctionTrigger fontSizeFunctionTrigger', function(e){ console.log(e); }); $('div').on('webkitAnimationEnd', function(e) { $(this).trigger(animEndTrigger(e)); }); 

JS Fiddle demo .

You can also use the called function either to fire the event itself, or to evaluate the passed parameters to determine if the event should be returned at all:

One evaluation method for a specific event to trigger is to use an object:

 var animations = { 'bgAnim': 'aParticularEvent' }; function animEndTrigger(e) { if (!e) { return false; } else { var animName = e.originalEvent.animationName; return animations[animName] ? animations[animName] : false; } } $('body').on('aParticularEvent', function(e) { console.log(e); }); $('div').on('webkitAnimationEnd', function(e) { $(this).trigger(animEndTrigger(e)); });​ 

JS Fiddle demo .

Although in this case, the return false parameter must be changed so as not to provide an Uncaught TypeError: Object false has no method 'indexOf' (which I have not bothered to take into account).

The following calls the called function ( animEndTrigger() ) directly to the trigger() custom event (which requires an element to bind the trigger() method), and also avoids the Uncaught TypeError above:

 var animations = { 'bgAnim': 'aParticularEvent' }; function animEndTrigger(e, el) { if (!e || !el) { return false; } else { var animName = e.originalEvent.animationName; if (animations[animName]) { $(el).trigger(animations[animName]); } } } $('body').on('aParticularEvent', function(e) { console.log(e); }); $('div').on('webkitAnimationEnd', function(e) { animEndTrigger(e, this); });​ 

JS Fiddle demo .

Of course, you still use if effectively to conduct the evaluation, so I cannot be particularly sure that this is better than your own already implemented solution.

+4
source

Source: https://habr.com/ru/post/925786/


All Articles