Events and addEventListener

Updated · 8 min read
mediumES2026javascripteventsaddeventlistenerdominterview

An event is a signal that something happened on the page: a click, a key press, a form submission, the page finishing loading. An event listener (or handler) is a function you register to run when a particular event happens on a particular element. Events are how a page becomes interactive: almost every line of front-end JavaScript runs because some event triggered it. The standard way to listen is addEventListener.

In One Minute

  • element.addEventListener("click", handler) runs handler each time the element is clicked.
  • The handler receives an event object with details: event.type, event.target, event.key, coordinates and more.
  • Remove a listener with removeEventListener using the same function reference, or with an AbortController signal.
  • Options: { once: true } runs it one time; { signal } removes it on abort; { passive: true } promises not to call preventDefault.
  • Inline onclick="..." attributes and element.onclick = fn are older ways; prefer addEventListener.

addEventListener

Syntax

syntax.js
element.addEventListener(type, listener, options);
ArgumentMeaning
typeThe event name, as a string: "click", "input", "submit", "keydown"...
listenerThe function to call; it receives the event object
optionsOptional: { once, passive, capture, signal }

Example

click.html
<button id="pay" type="button">Record payment</button>
<p id="status">No payments yet</p>
<script>
  let count = 0;
  const status = document.querySelector("#status");

  document.querySelector("#pay").addEventListener("click", () => {
    count++;
    status.textContent = `${count} payment(s) recorded`;
    console.log(status.textContent);
  });
</script>
Output
1 payment(s) recorded
2 payment(s) recorded

The checker clicked the button twice; each click ran the listener once. You can add many listeners to the same element and event: they all run, in the order they were added.

Common Event Types

CategoryEvents
Mouse and pointerclick, dblclick, contextmenu, pointerdown, pointerup, pointermove, pointerenter, pointerleave
Keyboardkeydown, keyup
Focusfocus, blur, focusin, focusout
Forminput, change, submit, reset, invalid
PageDOMContentLoaded, load, beforeunload, pagehide, visibilitychange
Windowresize, scroll, online, offline
Clipboardcopy, cut, paste
Animationtransitionend, animationend

The Event Object

Every listener receives an event object describing what happened. The properties depend on the event type, but a few are on every event:

Property or methodMeaning
event.typeThe event name, such as "click"
event.targetThe element where the event started (the exact thing clicked)
event.currentTargetThe element whose listener is running now
event.timeStampWhen it happened, in milliseconds since the page loaded
event.preventDefault()Stops the browser's default action (following a link, submitting a form)
event.stopPropagation()Stops the event from reaching ancestors (next lesson)
event.isTrustedtrue for real user actions, false for events created by scripts
event-object.html
<button id="save" type="button">Save <strong>now</strong></button>
<script>
  document.querySelector("#save").addEventListener("click", (event) => {
    console.log(event.type);
    console.log(event.target.tagName, event.currentTarget.tagName);
    console.log(event.isTrusted);
  });
</script>
Output
click
STRONG BUTTON
true

Explanation: the checker clicked the word "now", which is a <strong> inside the button. event.target is the innermost element clicked (STRONG); event.currentTarget is the element the listener is attached to (BUTTON). This distinction drives event delegation, covered in the next lesson.

Preventing Default Actions

Many events have a default action the browser performs after the listeners run: a link navigates, a form submits and reloads the page, a checkbox toggles. event.preventDefault() cancels it:

prevent.html
<a id="help" href="https://example.com/help">Help</a>
<script>
  document.querySelector("#help").addEventListener("click", (event) => {
    event.preventDefault();
    console.log("Showing help in the page instead of navigating");
    console.log(event.defaultPrevented);
  });
</script>
Output
Showing help in the page instead of navigating
true

The most common use is form submission: form.addEventListener("submit", (e) => { e.preventDefault(); ... }) lets JavaScript handle the data without reloading the page (see the forms lesson).

Removing Listeners

removeEventListener must receive the same function that was added. An inline arrow can't be removed, because a second identical-looking arrow is a different function:

remove.html
<button id="b" type="button">Click</button>
<script>
  const button = document.querySelector("#b");
  let clicks = 0;

  function onClick() {
    clicks++;
    console.log("click", clicks);
    if (clicks === 2) button.removeEventListener("click", onClick);
  }
  button.addEventListener("click", onClick);
</script>
Output
click 1
click 2

The third click did nothing: the named function onClick was removed after the second.

once and signal

Two options make removal easier:

once-signal.html
<button id="welcome">Welcome</button>
<button id="track">Track</button>
<button id="stop">Stop tracking</button>
<script>
  document.querySelector("#welcome").addEventListener("click", () => console.log("welcome shown"), { once: true });

  const controller = new AbortController();
  document.querySelector("#track").addEventListener("click", () => console.log("tracked"), { signal: controller.signal });
  document.querySelector("#stop").addEventListener("click", () => controller.abort());
</script>
Output
welcome shown
tracked

{ once: true } removes the listener after its first run. { signal } removes it when the AbortController is aborted; one controller can remove many listeners at once, which is ideal when a whole component is closed. (AbortController also cancels network requests; see the lesson on canceling and timeouts.)

The Older Ways

You'll still see two older styles:

older.html
<!-- 1. Inline attribute: JavaScript inside HTML (avoid) -->
<button onclick="pay()">Pay</button>
 
<script>
  // 2. Event handler property: only ONE handler per event
  const button = document.querySelector("button");
  button.onclick = () => console.log("first");
  button.onclick = () => console.log("second"); // replaces the first
</script>
addEventListenerel.onclick = fnonclick="..." attribute
Several handlers per eventYesNo (each assignment replaces)No
Options (once, signal, passive, capture)YesNoNo
Keeps JavaScript out of HTMLYesYesNo
Allowed by a strict Content Security PolicyYesYesNo

Inline attributes also run code built from a string, which strict security policies block. Use addEventListener.

In Practice

The Fee Tracker's payment buttons record a payment, disable themselves to prevent double-clicks, and clean up all listeners when the "Close" button is used:

buttons.html
<button id="pay-navika" data-name="Navika" data-amount="120">Pay for Navika</button>
<button id="pay-advitha" data-name="Advitha" data-amount="45">Pay for Advitha</button>
<button id="close">Close</button>
<script>
  const controller = new AbortController();
  const { signal } = controller;

  for (const button of document.querySelectorAll("[data-name]")) {
    button.addEventListener("click", (event) => {
      const { name, amount } = event.currentTarget.dataset;
      event.currentTarget.disabled = true;
      console.log(`Recorded $${amount} for ${name}`);
    }, { signal });
  }

  document.querySelector("#close").addEventListener("click", () => {
    controller.abort();
    console.log("Payment buttons closed");
  }, { once: true });
</script>
Output
Recorded $120 for Navika
Payment buttons closed

The second click on Navika's button did nothing because the button was disabled. After "Close", the listeners were removed, so clicking Advitha's button did nothing either.

Common Mistakes

Calling the handler instead of passing it. addEventListener("click", save()) runs save immediately. Pass save.

Removing an anonymous function. removeEventListener("click", () => ...) removes nothing. Keep a reference, or use once or signal.

Using event.target when you mean the element with the listener. Use event.currentTarget.

Writing event names with "on". addEventListener("onclick", ...) never fires. The name is "click".

Interview Corner

What is the difference between event.target and event.currentTarget?

target is the node where the event originated (the innermost element clicked). currentTarget is the element whose listener is currently executing, which differs from target when the event bubbles up from a descendant. currentTarget is only set during dispatch; it's null afterward.

Why prefer addEventListener over onclick?

It allows multiple listeners for the same event, supports options (once, passive, capture, signal), keeps behavior out of HTML, and works with Content Security Policy, which blocks inline handlers. Assigning onclick replaces any previous handler.

Practice

Challenge: Make a button that counts clicks and stops responding after 3, using the signal option instead of removeEventListener.

Show solution
limit.html
<button id="b">Vote</button>
<script>
  const controller = new AbortController();
  let votes = 0;
  document.querySelector("#b").addEventListener("click", () => {
    votes++;
    console.log("vote", votes);
    if (votes === 3) controller.abort();
  }, { signal: controller.signal });
</script>
Output
vote 1
vote 2
vote 3

Quick check: Events

3 questions
1What does addEventListener("click", save()) do?
2A button contains an icon. The icon is clicked. What is event.target?
3Which option removes a listener after its first run?

Key Takeaways

TaskCode
Listenel.addEventListener("click", handler)
One time{ once: true }
Remove later{ signal: controller.signal } then controller.abort()
Stop defaultevent.preventDefault()
Element with the listenerevent.currentTarget

Was this tutorial helpful?

Lesson 73 of 139