I have been trying to toggle an animation on and off using the .toggleClass. Unfortunately everything works well untill the first animation is complete. The problem is in the remaining animation class on element. I want to completely reset the element's class after applying an animation to it so that when I click on the button again I will not have to double click to remove and run the animation again. I have tried to strip down the animation classes after every animation has been done but have had no success. Somehow removing the class after it has been toggled forces it on the element and I couldn't find a way around it. Basicly, I want to remove the "necessary" double clicking so that I can run the animation again and remove all animation classes toggled on element after the animation has been successful.
Here's the link to jsfiddle.
//HTML
<div class="box"></div>
<button class="animationleft">left</button>
<button class="animationright">right</button>
//CSS
.box{
width:100px;
height:100px;
margin-left:350px;
background-color:black;
}
.slideRight {
-webkit-animation: slideRight 500ms cubic-bezier(0.19, 1, 0.22, 1);
}
.slideLeft {
-webkit-animation: slideLeft 500ms cubic-bezier(0.19, 1, 0.22, 1);
}
@-webkit-keyframes slideRight{
0% { opacity: 1; }
49% { opacity: 0; margin-left:70%}
50% { opacity: 0; margin-left:-70%}
100% { opacity: 1; }
}
@-webkit-keyframes slideLeft{
0% { opacity: 1; }
49% { opacity: 0; margin-left:-70%}
50% { opacity: 0; margin-left:70%}
100% { opacity: 1; }
}
$('.animationleft').on('click', function(){
$('.box').toggleClass('slideLeft');
setTimeout(function(){
$('.box').removeClass('.slideRight');
$('.box').removeClass('.slideLeft');
},500);
});
$('.animationright').on('click', function(){
$('.box').toggleClass('slideRight');
setTimeout(function(){
$('.box').removeClass('.slideRight');
$('.box').removeClass('.slideLeft');
},500);
});
The catch with CSS animation is that it doesn't provide a way to re-start your animation unless the animation class is removed then re-applied (which you're doing in your case with limited success) or the animated element itself is re-inserted.
I think the latter would probably give you a cleaner solution. The idea is to remove the box element from the page entirely when the animation is done and re-insert it.
The simple jQuery code routine you can use is as below:
var el = $('#box'), // I switched the 'box' class to an 'id'
newEl = el.clone(true); // make a clone of the element
el.before(newEl); // place the clone
$("." + el.attr("class") + ":last").remove(); // remove the "old" box
Here's a working demo (Updated): http://jsfiddle.net/H37CQ/3/
Update #3: http://jsfiddle.net/H37CQ/8/