Skip to content
Justice Tech School

Event Listeners

addEventListener attaches a function to an event. The function receives an event object with details such as event.target (the element) and event.key (the pressed key). preventDefault stops the default action, for example a form submit.

Listeners can be removed with removeEventListener, so keep a reference to the function.

Example
const out = document.getElementById("demo");
const input = document.createElement("input");
input.placeholder = "Type here";
document.body.prepend(input);
input.addEventListener("input", (event) => {
  out.textContent = "You typed: " + event.target.value;
});
input.addEventListener("keydown", (event) => {
  if (event.key === "Enter") out.textContent = "Enter pressed";
});

Exercise

Stop the default action of the event.

event.();

Quiz Test

What does event.target give you?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.