Reputation: 401
I have a plane that I want to fly back and fourth infinitely. I have a Javascript listener for animationend
that works just fine (I think.) It flies right, left, right, and then stops and resets at it's original position. When the listener fires, I just have it switch classes that are linked to the animations I want.
Here's the Javascript:
var runway = document.getElementById("myNavbar");
var plane = document.createElement('div');
plane.id = "plane";
plane.className = "plane-right";
runway.appendChild(plane);
$("#plane").one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(){
if (plane.className == "plane-right")
{
plane.className = "plane-left";
}
else
{
plane.className = "plane-right";
}
});
I also understand there's a jQuery toggle()
function but I can't get it to work. I tried $("#plane").toggle(".plane-right, .plane-left")
inside the listener but that didn't do the trick.
And the CSS class
.plane-right {
background-image: url("../img/zoomzoom.png");
background-position: center;
background-repeat: no-repeat;
background-size: 100%;
height: 50px;
width: 100px;
animation-name: moveLeftToRight;
animation-duration: 10s;
position: relative;
animation-timing-function: linear;
pointer-events: none;
}
.plane-left {
background-image: url("../img/zoomzoom.png");
background-position: center;
background-repeat: no-repeat;
background-size: 100%;
height: 50px;
width: 100px;
-moz-transform: scaleX(-1);
-o-transform: scaleX(-1);
-webkit-transform: scaleX(-1);
transform: scaleX(-1);
filter: FlipH;
-ms-filter: "FlipH";
animation-name: moveRightToLeft;
animation-duration: 10s;
position: relative;
animation-timing-function: linear;
pointer-events: none;
}
@keyframes moveLeftToRight {
from { left: -20%; }
to { left: 110%; }
}
@keyframes moveRightToLeft {
from { left: 110%; }
to { left: -20%; }
}
Update: I added an alert()
to the listener, and the alert does not fire the last time the animation ends before the plane resets position. Not sure if this is significant or helpful, but there it is.
Upvotes: 0
Views: 186
Reputation: 9005
Use "on" instead of "one". Using "one" only triggers once, although in this case twice and I'm not 100% sure why. It may be multiple event types (webkitanimationend AND animationend), but I'd think those would happen one after another.
https://jsfiddle.net/ftgr6h1e/
$("#plane").on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(){
Now, in general, animating position is slow. Consider animating transform3D instead to use the GPU to redraw your plane.
Upvotes: 1