Is there a way to reverse the CSS animation when a class is removed? I'm trying to achieve this on my simple example here: https://codepen.io/MichaelRydl/pen/MWPvxex - How can I make the animation play in reverse when clicking the button that removes the class?
const elementTwo = document.getElementById("element-two");
const addButton = document.getElementById("add-button");
const removeButton = document.getElementById("remove-button");
addButton.addEventListener("click", () => {
elementTwo.classList.add("animated");
})
removeButton.addEventListener("click", () => {
elementTwo.classList.remove("animated");
})
button {
margin-top: 10px;
}
#element-one {
width: 500px;
height: 30px;
background-color: lightgrey;
border-radius: 8px;
positon: absolute;
}
.animated {
width: 100%;
height: 100%;
background-color: lightblue;
border-radius: 8px;
position: relative;
top: 0;
left: 0;
animation-name: animateWidth;
animation-duration: 0.4s;
}
@keyframes animateWidth {
0% {
width: 0%;
}
100% {
width: 100%;
}
}
<div>
<div id="element-one">
<div id="element-two"></div>
</div>
<button id="add-button">Add Class</button>
<button id="remove-button">Remove Class</button>
</div>
Specifically, I want the animation to play backwards when the second button removes the class that was added by the first button. Can anyone help me with this?
Thank you for your assistance.