Itsy Bitsy Bytes


on javascript, css

When animationEnd is not fired

I ran into a problem today with an animated action. It was part of a queue and the next command was triggered from inside the animationEnd callback.

The animations I was using were made with CSS classes and detecting the animation completion with Javascript was a much more elegant and adequate solution than triggering the end with a setTimeout forced to have the same duration as the animation. Sometimes the browser lags a little, sometimes the CSS animation gets stuck so animationEnd is a sure way to know everything is properly done.

However, the particular .css file with the said animation was not included. The animation was therefore not done and the callback not triggered. Since it was a situation were such errors might happen again, due to the large amount of animations available and the sane way of not including them all by default, I had to find a solution to avoid such problems in the future.

Unfortunately, I didn't found any equivalent of onError for animationEnd so the only thing left to be done was to check if the CSS class with the animation exists inside the stylesheet.

This StackOverflow answer was a great starting point. By accessing document.styleSheets one has access to the selector text and can search for the class name. You just need to loop trough document.styleSheets[].rules[].selectorText and document.styleSheets[].imports[].rules[].selectorText.

The selectorText property returns the selector exactly as it is inside the css file so the matching part is a bit tricky.

First of all, the . must be placed in front of the class and second, a simple === is not enough, as you can have multiple class names separated by a comma, for example. For my needs, the equality test was enough but for a proper solutin some regular expressions might be required.

Anyway, this did the trick for me. Before applying the animation I check for the class existence. If it does not exist, I throw a non-blocking custom error, so the developers (myself included) know exactly what's happening and what's the missing class, and continue with the action queue.

It might not be the greatest solution but it's a working solution!


comments powered by Disqus