I'm new to Stack Overflow and also relatively new to HTML5 programming. I'm writing something (for Safari, primarily) where the logic is driven by the events which get fired out when webkit animations complete. If I start a number of animations of the same length simultaneously, I need some idea of the order I can expect their completion events to fire. Example:
<!DOCTYPE html>
<html>
<head>
<style>
@-webkit-keyframes slideRight {
from { left: 0; }
to { left: 100px; }
}
</style>
</head>
<body>
<script type="text/javascript">
var square = function(yPos, color){
var myDiv = document.createElement("div");
myDiv.style.width = "20px";
myDiv.style.height = "20px";
myDiv.style.top = yPos + "px";
myDiv.style.backgroundColor = color;
myDiv.style.position = "absolute";
document.body.appendChild(myDiv);
var squareInterface = {
onAnimEnd: function(event){
console.log(myDiv.style.backgroundColor + " square finished animating");
},
startAnim: function(){
myDiv.style.webkitAnimationName = "slideRight";
myDiv.style.webkitAnimationDuration = "2s";
myDiv.addEventListener('webkitAnimationEnd', this.onAnimEnd);
}
}
return squareInterface;
}
var myRedFoo = square(0, "red");
var myBlueFoo = square(30, "blue");
myRedFoo.startAnim();
myBlueFoo.startAnim();
</script>
</body>
</html>
So, I'm creating a red square and a blue square in JavaScript, and (in Safari and Chrome) kicking off animations to move them to the right, and to print to the console when they're done. The blue square is always the first to say that it's finished animating. From playing around it seems to have nothing to do with the order in which the animations were started, or the positions of the squares, but the order in which they're created. "Simultaneous" event callbacks seem to occur on the most recently created element first, followed by the older elements.
My question is can I rely on this behaviour? Is it guaranteed in any standards, or is it likely to change depending on the browser, or the phase of the moon? If the event order can't be guaranteed, what strategies would you recommend for coping with that?