I have the following game and the css green block is failing to jump on click. I can’t seem to spot my error.
As you can see I have added the onclick event in the HTML and as far as I know the css animation is correctly coded in the style file. I want the character to jump calling the CSS animation, and ideally avoid a JScript function at this stage (or have both alternatives to see which is simpler for young students)
Can anyone spot and point out the error please.
* {
padding: 0;
margin: 22;
}
#game {
width: 500px;
height: 500px;
border: 4px solid #f74cbc
}
#character {
width: 30px;
height: 120px;
background-color: green;
position: relative;
top: 380px;
border-radius: 20px;
animation: jump 500ms;
}
#enemy {
width: 60px;
height: 60px;
background-color: red;
border-radius: 10px;
position: relative;
top: 320px;
left: 440px;
animation: moveenemy 1s infinite linear;
}
@keyframes jump {
0% {
top: 380px;
}
30% {
top: 200px;
}
50% {
top: 200px;
}
100% {
top: 380px;
}
}
@keyframes moveenemy {
0% {
top: 440px;
}
50% {
top: 58px;
}
100% {
left: 0px;
top: 320px;
}
}
<!DOCTYPE html>
<html lang="en" onclick="jump()">
<head>
<meta charset="UTF-8">
<title>Battle</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>TG</h1>
<p>Avoid the red</p>
<div id="game">
<div id="character"></div>
<div id="enemy"></div>
</div>
<script src="script.js"></script>
</body>
</html>
Update:
I know I could use a Jscript function like the below, but even that does not work?
JavaScript tried below (in the script.js)
function jump(){
if(character.classlist!="animate"){
character.classList.add("animate");
}
setTimeout(function(){
character.classList.remove("animate");
},500);
}
Ideally, as mentioned, I want the simplest possible solution. Could both errors be pointed out (solution provided) so both alternatives are present in the answer. Which is the recommended way?
You could toggle a
CSS
class with javascript that executes your jump animation. You can’t reference aCSS
animation directly viaJS