The Event Object

Grade 12, page 4 of 9. A one-minute read.

When the browser runs your callback, it passes in a special object with information about what just happened. It's called the event object, and it's usually named event or just e:

JavaScript
button.addEventListener("click", (event) => {
  console.log(event.type);    // "click"
  console.log(event.target);  // the element that was clicked
});

The most useful property is event.target: the element where the event happened. There are also properties specific to each kind of event. For keyboard events, event.key tells you which key was pressed:

JavaScript
document.addEventListener("keydown", (event) => {
  console.log(`You pressed: ${event.key}`);

  if (event.key === "Enter") {
    console.log("Enter! Submitting...");
  }
  if (event.key === "ArrowUp") {
    console.log("Moving up! ⬆️");
  }
});

We attached this listener to the whole document, so it catches key presses anywhere on the page. Try pressing letters, numbers, arrow keys and Enter, and watch the console. This is how browser games handle keyboard controls!

For mouse events, event.clientX and event.clientY tell you exactly where the mouse pointer was on the screen, in pixels.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning