30 Days Of JavaScript

Day 17: Events

Lesson 4: keydown

You can detect if a specific key is pressed with the keydown event handler. Commonly used as a method in some old school hacks, to make it so entering a form works when you press the return key (not needed anymore but you may still come across it in older code bases) or in games.

Let's have some fun with moving a little ball around the screen.

Add this to your HTML

2  id="ball"
3  style="
4        left: 30px;
5        top: 30px;
6        position: absolute;
7        width: 30px;
8        height: 30px;
9        border-radius: 15px;
10        background-color: red;
11      "

and this to your JavaScript:

1const ball = document.getElementById("ball");
2const movement = 5;
4document.addEventListener("keydown", (e) => {
5  if (e.key === "ArrowRight") {
6    let left = parseInt(ball.style.left) + movement;
7    ball.style.left = `${left}px`;
8  }
9  if (e.key === "ArrowLeft") {
10    let left = parseInt(ball.style.left) - movement;
11    ball.style.left = `${left}px`;
12  }
13  if (e.key === "ArrowUp") {
14  }
15  if (e.key === "ArrowDown") {
16  }

The first two lines are getting a reference to the div and setting an amount to move by.

Then we add an event listener to the main document, and detect when the arrow keys are pressed to then change the left and right margins of the ball.

Its a little clunky because we are moving in steps of 5px and we are adding no animations between locations but you can see how this allows us to move the ball around.

Your challenge is to fill in up and down 😊


Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co