addEventListener() (JavaScript)

addEventListener() tells an element to run a function whenever a specific event happens, such as a click or keypress. It is the standard way to make pages interactive.

JavaScript

You attach a listener to an element, name the event ("click", "input", "submit", etc.), and pass a callback that runs each time the event fires.

Unlike onclick, addEventListener lets you attach multiple handlers to the same event.

Syntax

element.addEventListener(event, callback)

Examples

JavaScript

const btn = document.querySelector("button");
btn.addEventListener("click", () => {
  console.log("Clicked!");
});

Output:

Clicked!  (each time the button is clicked)

Learn it in a lesson

See also

Back to the Dictionary