Handling events

JavaScript · Essentials · 12 min

Interactivity in the browser is entirely driven by events.

The browser fires events when things happen: clicks, key presses, input changes, form submissions, page load. You listen with addEventListener:

button.addEventListener("click", (event) => { ... });

The handler receives an event object describing what happened: event.target (the element where it originated), event.key for keyboard events, event.clientX for mouse position, and so on.

Some events have a default action: a link navigates, a form submits and reloads the page. Call event.preventDefault() to stop it, which is what you do when handling a form in JavaScript.

Common events to know:

  • click, dblclick, pointerdown, pointerup
  • input (fires on each change to a field) and change (when the edit is committed)
  • submit on a form — listen here rather than on the button so Enter also works
  • keydown, keyup
  • DOMContentLoaded on document, load on window

To remove a listener, call removeEventListener with the same function reference, so keep the handler in a variable. The options object can help: { once: true } removes it after the first call, and { signal } with an AbortController removes it when you call controller.abort().

Avoid inline onclick="..." attributes in HTML; they mix markup and behaviour and run in a confusing scope. Setting el.onclick = fn works but allows only one handler per event.

Read form values with input.value (always a string) or new FormData(form), which collects every named field at once.

Example

// Assumes: <form id="signup"><input name="email"><button>Join</button></form>
//          <p id="msg"></p>
const form = document.querySelector("#signup");
const msg = document.querySelector("#msg");

form.addEventListener("submit", (event) => {
  event.preventDefault();                 // don't reload the page
  const data = new FormData(form);
  const email = String(data.get("email")).trim();
  msg.textContent = email.includes("@") ? `Thanks, ${email}!` : "Invalid email";
});

form.email.addEventListener("input", (e) => {
  e.target.classList.toggle("empty", e.target.value === "");
});

function onFirstKey(e) { console.log("first key:", e.key); }
document.addEventListener("keydown", onFirstKey, { once: true });

Remember

  • addEventListener(type, handler) — the handler gets an event object
  • event.preventDefault() cancels default actions like form submission
  • Removing a listener needs the same function reference (or { once } / { signal })

Watch out for

  • Listening to a submit button's click instead of the form's submit, so pressing Enter bypasses your code.

Check yourself

  1. Why does this fail to remove the listener? btn.addEventListener("click", () => go()); btn.removeEventListener("click", () => go());

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener