After the introduction of the CSS3, we got a lot of new features including the transition and animation properties. With this two now we can make more complex animations with just CSS. We can bravely say that the CSS animation made a great process and now we can make some elegant interaction on our sites or applications.
One of the ways to make some callback is to use a timeout with the transition or animation interval when switching the class or the state. We know that this is not the best solution because of the browser’s optimized working processes.
Transitionend and Animationend
Depending on what type of animation method you use you have to use the correct event, this is self-evident. There is one pitfall, in the different browsers you might need different suffix (yep, this is prefixed, it is annoying in CSS, but it is more annoying in JS). There exist two simple helpers (from David Walsh) which help you identify the correct event name, the first is the transitionend and the second is the animationend.
Catch the Transitionend – Example
As you see in the below Pen, we made a simple element which toggles a class by click, but after the end, we also remove that class, so the item returns to the start position. With the use of transitionend, we can correctly catch the right moment for the class remove. Note that we removed the transitionend event listener after the event triggered so the next time it doesn’t duplicate.
Catch the Animationend – example
In this case, we simply made a simple display animation to show an item. We used keyframe, and in the JS we used the whichAnimationEvent() helper function, and we registered the animationend event directly to the element.
Nice to know that you won’t use this technique in your normal development, but it can be suitable. I developed a simple off-canvas navigation in the past days, and for the overlay, I had to catch the end of the opening animation so for me in that project it was a life saver. Of course there a lot of good JS library like the GSAP which is dropping this problem but on a smaller project for one particular problem I’m not sure you need a full library.
Keep in mind this excellent technique, and in the next time, it can be handy!