To create a simple event-trigger, you can pass a function to jQuery's trigger()
method and utilize the returned value of that function to initiate a specific event (which can then be detected:
function animationEndTrigger(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(animationEndTrigger(e));
});
JS Fiddle demo.
You can also use the called function to trigger the event itself or evaluate the passed parameters to decide whether or not to trigger an event at all:
One approach is to check for a specific event to trigger using an object:
var animations = {
'bgAnim': 'aParticularEvent'
};
function animationEndTrigger(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(animationEndTrigger(e));
});
JS Fiddle demo.
In this case, it's important to modify the return false
to prevent the error
Uncaught TypeError: Object false has no method 'indexOf'
(which hasn't been addressed yet).
The following approach allows the called function (animationEndTrigger()
) to directly trigger()
the custom event (requiring an element to bind the trigger()
method) while avoiding the aforementioned Uncaught TypeError
:
var animations = {
'bgAnim': 'aParticularEvent'
};
function animationEndTrigger(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) {
animationEndTrigger(e, this);
});
JS Fiddle demo.
While still relying on an if
statement for evaluation, it may not necessarily be cleaner than your current implementation.