Codectionary / Developer documentation / JavaScript

addEventListener() and the Event Object

addEventListener() attaches a function to run when a specific event occurs on an element, without overwriting any other listeners already attached (unlike the older onclick= style). The callback receives an Event object with details about what happened, including target (the element that triggered it) and methods like preventDefault().

Syntax

element.addEventListener("event", callback)

Examples

Basic Click Listener

Responding to a button click.

const button = document.querySelector("#myButton");

button.addEventListener("click", (event) => {
  console.log("Button clicked!");
  console.log("Target:", event.target);
});

preventDefault() and Form Submission

Stopping an event's default browser behavior.

const form = document.querySelector("#myForm");

form.addEventListener("submit", (event) => {
  event.preventDefault(); // stops the page from reloading
  console.log("Form submitted via JavaScript instead");
});

Multiple Listeners and removeEventListener()

Attaching several listeners and later removing one by reference.

function handleClick() {
  console.log("Clicked!");
}

const button = document.querySelector("#myButton");
button.addEventListener("click", handleClick);

// Later, stop listening - requires the SAME function reference
button.removeEventListener("click", handleClick);

// Anonymous functions cannot be removed this way, since a new reference is created each time

Best practices

  • Use addEventListener() instead of inline onclick= attributes or element.onclick = - it allows multiple listeners and cleaner separation of HTML and JavaScript
  • Keep a reference to named functions if you need to remove a listener later - removeEventListener() requires the exact same function reference
  • Call event.preventDefault() when you want to override default browser behavior, like a form submitting and reloading the page
  • Remove event listeners on elements that get removed from the DOM to avoid memory leaks in long-running applications

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading