...

/

Jumping Frog Animation and Cookie Grabber Game

Jumping Frog Animation and Cookie Grabber Game

Learn to implement animation by making a jumping frog, and then implement a cookie grabber game.

Animation

CSS provides a plethora of ways to animate elements using various transformations.

JavaScript can be used to make these animations more interactive. Let’s take a look at a simple example to see how it works.

Jumping frog

We’re going to use CSS animation to create a jumping frog effect. To start with, we need an element for our frog to go in the index.html file:

<div id='frog'>🐸</div>

Now let’s add some to the style.css file to get the frog into position:

#frog {
font-size: 64px;
position: absolute;
top: 100px;
}
Getting the frog into the position

This just makes the frog a bit bigger and gives it an absolute position on the page. To use CSS animations, we need to create a @keyframes rule that describes each frame of the animation. Let’s add the following to the styles.css file:

@keyframes jump {
to {
transform: translateY(-100px);
}
}
Describing each frame of the animation

This @keyframes rule only describes the end state of the animation, which is a vertical translation of 100px upwards (negative values move up in the Y direction). To make it come back down again, we’ll use the animation direction property with a value of alternate. This plays the animation forwards, then backwards, producing a jumping effect. Let’s add the following lines of code to the #frog selector’s styles:

animation-name: jump;
animation-duration: 700ms;
animation-iteration-count: infinite;
animation-direction: alternate;
Producing jump effect

We should see the frog jumping up and down like this:

We can use JavaScript to add some interactivity to this animation by adding an event handler to the frog element that will run the animation when a click occurs instead of just repeatedly running it. First of all, let’s remove the animation properties from the styles.css file and add the following code to the index.js file:

const frog = document.getElementById('frog');
document.addEventListener('click', e => frog.style.animation = 'jump 700ms 2 alternate')
Adding an event handler

This event listener will fire when the user clicks anywhere on the ...