CSS class isn't running when I add it in JS fike [closed]
Solution 1:
There are a couple of errors in your code. In the CSS part, you need to add an @
symbol in front of keyframes.
Also, you shouldn't animate the top
value and should prefer hardware accelerated properties like transform
. (see the example below)
.animate {
animation: jump 500ms;
}
@keyframes jump {
from {
transform: translateY(0);
}
to {
transform: translateY(-40px);
}
}
In the JS part, there is no global getElementById()
, you need to use document.getElementById()
to select your elements.
var player = document.getElementById("player");
var fruit = document.getElementById("fruit");
function jump() {
player.classList.add("animate");
setTimeout(function () {
player.classList.remove("animate");
}, 500);
}
var player = document.getElementById("player");
var btn = document.getElementById("btn");
function jump() {
player.classList.add("animate");
setTimeout(function() {
player.classList.remove("animate");
}, 500);
}
btn.addEventListener("click", jump);
.player {
background-color: #a1887f;
border-radius: 50%;
height: 3rem;
margin: 4rem auto 1rem;
width: 3rem;
}
button {
background-color: #c5e1a5;
border: 2px solid rgba(0, 0, 0, 0.1);
border-radius: 0.25rem;
color: rgba(0, 0, 0, 0.6);
cursor: pointer;
display: block;
font-size: 1.25rem;
margin: auto;
padding: 0.5rem 1rem;
}
.animate {
animation: jump 500ms;
}
@keyframes jump {
from {
transform: translateY(0);
}
to {
transform: translateY(-40px);
}
}
<div class="player" id="player"></div>
<button id="btn">Jump</button>