Currently I’m trying to start a second animation after stopping the first one. The first animation did manage to stop but the second animation won’t manage to start. I don’t know what is going wrong with my codes and I don’t know how to test to see which part is going wrong.
function flyRocket() {
let animatedElement = document.querySelector('.rocket');
animatedElement.style.animation = 'none';
moveRocket();
}
function moveRocket() {
let movingElement = document.querySelector('.rocket');
movingElement.classList.add('move-up-animation');
}
#Rocket {
height: 100px;
width: 50px;
}
.rocket {
position: relative;
animation: animate 0.5s ease infinite;
}
@keyframes animate {
0%, 100% {
transform: translateY(-4px);
}
50% {
transform: translateY(4px);
}
}
.rocket::before {
content: '';
position: absolute;
bottom: -40px;
left: 50%;
transform: translateX(-50%);
width: 10px;
height: 50px;
background: linear-gradient(#00d0ff, transparent);
}
.rocket::after {
content: '';
position: absolute;
top: 5;
left: 50%;
transform: translateX(-50%);
width: 10px;
height: 50px;
background: linear-gradient(#00d0ff, transparent);
filter: blur(20px);
}
.move-up-animation {
animation: moveUpAnimation 2s ease forwards;
}
@keyframes moveUpAnimation {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-50px);
}
}
<div class='scene'>
<div class='rocket'>
<img id='Rocket' src='rocket.png'>
</div>
</div>
Any help is appreciated.
>Solution :
split the animation from .rocket selector to another class – call it whatever, and add that class to the element. On the click, remove that class and add the class you are adding now
Like this
function flyRocket() {
let animatedElement = document.querySelector('.rocket');
animatedElement.classList.remove('up-down-animation');
moveRocket();
}
function moveRocket() {
let movingElement = document.querySelector('.rocket');
movingElement.classList.add('move-up-animation');
}
document.body.addEventListener('click', flyRocket);
#Rocket {
height: 100px;
width: 50px;
}
.rocket {
position: relative;
}
.up-down-animation {
animation: animate 0.5s ease infinite;
}
@keyframes animate {
0%, 100% {
transform: translateY(-4px);
}
50% {
transform: translateY(4px);
}
}
.rocket::before {
content: '';
position: absolute;
bottom: -40px;
left: 50%;
transform: translateX(-50%);
width: 10px;
height: 50px;
background: linear-gradient(#00d0ff, transparent);
}
.rocket::after {
content: '';
position: absolute;
top: 5;
left: 50%;
transform: translateX(-50%);
width: 10px;
height: 50px;
background: linear-gradient(#00d0ff, transparent);
filter: blur(20px);
}
.move-up-animation {
animation: moveUpAnimation 2s ease forwards;
}
@keyframes moveUpAnimation {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-50px);
}
}
<div class='scene'>
<div class='rocket up-down-animation'>
<img id='Rocket' src='rocket.png'>
</div>
</div>