I'm struggling to make this cool "rotating ball" animation start and stop based on any key being held down. The animation should only play while a key is actively pressed.
I've done some research, but I keep coming across jQuery solutions that I'm not familiar with. I feel like I might be missing something in my JavaScript code, but as you can tell, I'm pretty new to all of this and still trying to figure it out.
(I know I've assigned the keypress
event to "Q", but ideally, I'd like the animation to begin as soon as any key is pressed and pause when the key is released. Additionally, I want the animation to repeat multiple times rather than stopping after just one loop.)
const start = document.querySelector("#ball");
const rot = document.querySelector("#roter");
window.addEventListener("keydown", move)
function move(event) {
if (event.key !== "") {
ball.style.animation = "roll 4s linear running";
roter.style.animation = "rotate 4s linear running";
} else {
ball.style.animation = "roll 4s linear paused";
roter.style.animation = "rotate 4s linear paused";
}
};
.line{
width: 1000px;
height: 500px;
}
#ball{
position: relative;
top: 40px;
left: 0;
width: 100px;
height: 100px;
background-color: rgb(114, 240, 214);
border-radius: 50%;
animation-play-state: paused;
text-align: center;
line-height: 100px;
}
/* .ball:hover{
animation-play-state: paused;
}
-#roter:hover{
animation-play-state: paused;
} */
@keyframes roll {
0%{
top: 40px;
left: 0;
transform: rotate(0deg);
}
12.5%{
top: 40px;
left: 50px;
transform: rotate(45deg);
}
25%{
top: 40px;
left: 100px;
transform: rotate(90deg);
}
37.5%{
top: 40px;
left: 150px;
transform: rotate(135deg);
}
50%{
top: 40px;
left: 200px;
transform: rotate(180deg);
}
62.5%{
top: 40px;
left: 250;
transform: rotate(225deg);
}
75%{
top: 40px;
left: 300px;
transform: rotate(270deg);
}
87.5%{
top: 40px;
left: 350px;
transform: rotate(315deg);
}
100%{
top: 40px;
left: 250px;
transform: rotate(360deg);
}
}
#roter{
animation-name: roter;
animation-play-state: paused;
}
@keyframes roter {
0%{
}
25%{
transform: rotate(90deg);
}
50%{
transform: rotate(180deg);
}
75%{
transform: rotate(270deg);
}
100%{
transform: rotate(360deg);
}
}
<div class="line">
<div id="ball">
<p id="roter">161519</p>
</div>
</div>