Take a look at the snippet below and you'll see that the sliding animation plays twice - once when the .addClass statement runs, and again when #test's display is switched to 'initial' (timeouts are in place to help visualize the issue):
$(() => {
$('#test').addClass('animate');
setTimeout(() => {
$('#test').css({ display: 'none' });
setTimeout(() => {
$('#test').css({ display: 'initial' });
}, 1000);
}, 1000);
});
#test {
position: relative;
left: 0;
}
#test.animate {
animation: move 1s ease forwards;
}
@keyframes move {
100% {
left: 100px;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="test" src="https://cdn4.buysellads.net/uu/1/3332/1524843316-62666.png">
What causes an element's animation to replay when changing its display attribute from 'none' to a visible state ('initial', 'block', etc.) using JavaScript, and how can this be prevented?
Note: setting animation-fill-mode to 'forwards' is a requirement.