How can I use the CSS animation when the class is removed?
If you look on my easy example here: https://codepen.io/MichaelRydl/pen/MWPvxex – how can I achieve, that the animation run (but reversed) on clicking the button which 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>
To be concrete, when I press the first button from the example, it adds the class to the element and runs the width animation, but I don’t know how can I run the backward animation when I press the second button from the example which removes the class.
Thanks for your help.
2
Answers
It seems like you are actually after a
transition
:Furthermore as a bonus, you could consider using
transform: scaleX()
instead for better animation performance, aswidth
means the browser has to do layout, compositing and painting whereastransform
the browser only has to do compositing and painting:You need to move the transition/animation to the element that you want the effect on so that it fires both when added and removed. See: