Is it possible to animate a div to the right when a button is clicked, then animate back to the left with just one keyframes declaration by swapping classes?
While attempting this in CodePen, I encountered an issue where the div snaps back after the first animation and fails to animate again the second time.
I opted not to use CSS transitions so that I could incorporate features of CSS animations such as a bouncing effect.
window.addEventListener("load", function() {
var movedOver = false;
document.querySelector("button").addEventListener("click", function() {
var buttonEl = document.querySelector(".one");
if (movedOver) {
buttonEl.classList.remove("do-the-slide");
buttonEl.classList.add("do-the-slide-back");
} else {
buttonEl.classList.remove("do-the-slide-back");
buttonEl.classList.add("do-the-slide");
}
});
});
.container {
position: absolute;
perspective: 800px;
>div {
position: absolute;
padding: 20px;
text-align: center;
width: 100px;
}
>div.do-the-slide {
animation: moveOver 1s ease-out;
}
>div.do-the-slide-back {
animation: moveOver 1s reverse ease-out;
}
>.one {
background: red;
}
}
button {
margin-top: 100px;
}
@keyframes moveOver {
from {
transform: translateX(0px);
}
to {
transform: translateX(100px);
}
}
<div class="container">
<div class="one">One</div>
</div>
<button>Clicky</button>
Codepen: http://codepen.io/anon/pen/Vaadao