How can the end event of a custom CSS animation be bound using jQuery or JavaScript?

We are currently managing multiple animations on the same object and need to execute different actions once each animation is complete.

At present, we listen for the webkitAnimationEnd event and use a complex if/then statement to handle each animation separately.

Is there a way to create custom webkitAnimationEnd events so that we can trigger a specific event handler when a particular animation finishes? For example, executing handler1 when animation1 finishes and handler2 when animation2 finishes.

We are developing for Webkit browsers, particularly Mobile Safari.

Thank you!

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to locate a route for the React styled components image

I'm having trouble locating the correct path for the image in my React styled components. I believe the path is correct, but could the issue be related to styled-components? Check it out here import styled from "styled-components"; export defaul ...

The Bootstrap data-target and aria-controls attributes are failing to activate the designated id element

I have implemented various elements to toggle the display of information on my HTML website. While I've successfully created buttons, nav-tabs, and modals, clicking on the trigger element doesn't reveal the associated content. I've even doub ...

Is there a way to navigate through div text within a stationary container?

My current challenge involves a container that contains an overflow of text, but I desire for the container to remain fixed. The dilemma arises when the text spills out from both the top and bottom edges of the container. Instead of using scroll bars withi ...

Closing WebSocket connection after sending data

I came across an interesting blog post titled Experimenting with Node.js and decided to try setting it up on my own using the author's provided gist. Unfortunately, I encountered some issues. After further investigation, I discovered that even though ...

CSS animations are failing to work properly in Firefox due to a pseudo-element issue

I'm encountering a problem with my CSS animations in Firefox. Specifically, the animations are not working on a pseudo element (:after) while they work perfectly fine on other browsers. Below is where the animations are being applied: :after { d ...

Using Vue.js for instant field validation when sending PHP post forms for enhanced user experience

A unique approach is being taken to utilize vue.js exclusively for real-time field validation, while the form will ultimately be submitted using PHP through the POST method. However, a challenge arises where vue.js takes control of the form, hindering PHP& ...

The scroll bar remains hidden even though there are additional elements waiting to be displayed

I am currently utilizing asp.net along with entity framework 4 On my page, I have three tabs structured like this: The Challenge I'm Facing The issue I am encountering is that the browser fails to display a scrollbar even when there are over 150 ro ...

Complicated "as-label" for understanding expressions in Angular

Is it possible to set a complex label in a comprehension expression in Angular? I've searched everywhere for a solution, but I can't seem to find one. The workaround I found involves pre-populating the 'as' label attribute with the des ...

Hosting completely disregards CSS class

Hey there, I'm currently facing an issue with my CSS file that contains all the styling for about ten different pages. The problem lies in the fact that the CSS classes are not being applied as they should be. Specifically, I have p tags within the ...

Chrome is blocking my ajax cross-origin request, causing it to be cancelled

I have been working on a Google Chrome extension and encountering an issue with my ajax requests. Every time my extension sends a request, it ends up getting cancelled for some unknown reason. The following code snippet seems to be functioning properly: ...

Can you explain the distinction between using $.ajax and $.post in jQuery?

Within my project, there are both calls made using $.ajax as well as some utilizing $.post. I am under the impression that these two types of calls are essentially identical! Can anyone confirm if this understanding is accurate? ...

How can I merge an array of objects in lodash?

I am facing a challenge with merging an array of objects in JavaScript. My goal is to combine them into a single object using either a JS library or lodash. Here is how my array looks: [{ 2017: { a: "100", b: "200" ...

Choose Your Preferences When the Page Loads

I have a dropdown menu where I can select multiple options at once without checkboxes. When the page loads, I want all of the options to be pre-selected by default. I am aware that I can use $(document).ready() to trigger actions after the page has load ...

Access denial encountered when attempting to submit upload in IE8 using JavaScript

When running the submit function on IE8, I am receiving an "access is denied" error (it works fine on Chrome and Firefox for IE versions above 8): var iframe = this._createIframe(id); var form = this._createForm(iframe, params); ... ... ...

Modifying the geometry of a plane in Three.js

Currently working on a simple terrain editor. When the mouse is clicked, I want the selected face to move up. The intersection is functioning well, and I am attempting to adjust the geometry in this manner: var intersects2 = ray.intersectObjects([ ...

Align three divs with three columns in the horizontal center

I am facing a challenge where I need to perfectly center 3 col3 divs in a row. Despite the calculation showing 1.5, I am unsure of the proper method to overcome this hurdle. <div class="row"> <div class="col-md-offset-2 col-md-3" style="height: ...

The floated div is disrupting the flow due to its margin

Two divs are causing some alignment issues: one floated left and the other floated right. The margin on the right div is pushing it down, causing the left div to appear lower than desired. I want both divs to be aligned at the top of the page. HTML: < ...

The Nivo slider seems to be behaving strangely when utilized with the fadeIn() jQuery animation

The page's basic structure, simplified to the extreme, looks something like this: <div id="content"> <div id="nivo"> Nivo slider content goes here </div></div> I'm attempting to add animation to the #content div using th ...

Show or hide content using handlebars based on a user's role

In the project I am working on, there are two distinct users - employers and candidates. var User = new Schema({ role:String }); I want to customize certain elements on my handlebars page based on the logged-in user. These elements include font-aweso ...

tips for sending types as properties in a versatile component

I am facing a challenge with passing types as props to a reusable component. I have a component where I pass rows and headings as props, but I need to find a way to pass types as props as well. Below is the code for my reusable component: import { TableCe ...