I'm trying to create a CSS animation when a user clicks on an element that he animates on the right, and then when he clicks on it again, he animates to the left. The problem is that it starts to flicker. I know the reason, but I'm not sure if this is the best way to fix it. I want the most elegant solution to this problem.
I install jsFiddle (WebKit only) here: http://jsfiddle.net/4Ad5c/2/
CSS:
.animateRight{ -webkit-animation: goRightLeft 1s; -webkit-animation-fill-mode: forwards; } .animateLeft{ -webkit-animation: goRightLeft 1s; -webkit-animation-fill-mode: backwards; -webkit-animation-direction: reverse; } @-webkit-keyframes goRightLeft { 0%{margin-left: 0px;} 100%{margin-left: 100px;} }
JavaScript:
this.animateBox = function(className){ var box = document.getElementsByClassName('box')[0]; box.className = "box"; setTimeout(function(){ box.className = "box " + className; },1); };
When you click the Animation Right button, it works as expected, but when you click the Animation Left button, it flickers to the left and then animates as expected. The reason is that you need to remove the class and add another to animate the animation, but I don't know how best to do it. I believe that I could add a class when deleting a previous animation that has it in its current state, but that seems wrong to me.
Thanks for the help!
source share