Skip to content

Event Handling

Handle browser events with addEventListener, delegation, and the event object.

What you'll learn

  • How to listen for events with addEventListener
  • The event object and its useful properties (target, currentTarget, preventDefault)
  • Event delegation for handling many elements with one listener
  • Common event types: click, input, submit, keydown, DOMContentLoaded

Concept

Event Handling

An event is something that happens in the browser — a user clicks a button, types in a field, submits a form, presses a key, or the page finishes loading. Event handling is how your JavaScript responds to these events. You register a listener that says "when this event happens on this element, run this function." This is the bridge between user actions and your code.

addEventListener

The standard way to listen for events is element.addEventListener(type, handler):

const button = document.querySelector("#my-button");
button.addEventListener("click", (event) => {
  console.log("Button clicked!", event.target);
});

The handler receives an event object with details about what happened. event.target is the element that triggered the event. event.preventDefault() stops the default action (like preventing a form from submitting). Always use addEventListener — never the inline onclick attribute, which mixes HTML and JS and only allows one handler.

The Event Object

The event object carries useful information:

  • event.target — the element that actually triggered the event (may be a child of the element with the listener).
  • event.currentTarget — the element the listener is attached to.
  • event.preventDefault() — cancels the default browser behavior (e.g., stop a link from navigating).
  • event.stopPropagation() — stops the event from bubbling up to parent listeners.
  • event.key — which key was pressed (for keyboard events).

Event Delegation

Instead of adding a listener to every item in a list, add one listener to the parent and use event.target to find which child was clicked. This is event delegation, and it is one of the most powerful patterns in DOM programming:

list.addEventListener("click", (e) => {
  if (e.target.matches(".delete-btn")) {
    e.target.closest("li").remove();
  }
});

This works for items added dynamically later — no need to re-attach listeners. One listener handles hundreds of items.

Common Event Types

  • click — mouse click (or tap on mobile).
  • input — fires on every keystroke in a text field (use for live search).
  • change — fires when a field loses focus and its value changed (use for select menus).
  • submit — fires when a form is submitted. Always call preventDefault() to handle it with JS.
  • keydown / keyup — keyboard key pressed/released.
  • DOMContentLoaded — the DOM is ready (use instead of window.onload for faster startup).

Example

              // Event delegation: one listener handles all delete buttons
const list = document.querySelector("#item-list");

list.addEventListener("click", (event) => {
  // Check if the clicked element (or its ancestor) is a delete button
  const deleteBtn = event.target.closest(".delete-btn");
  if (deleteBtn) {
    const item = deleteBtn.closest("li");
    item.remove();
    return;
  }

  // Handle edit button clicks
  const editBtn = event.target.closest(".edit-btn");
  if (editBtn) {
    const item = editBtn.closest("li");
    const text = item.querySelector(".item-text").textContent;
    openEditor(text, item);
  }
});

// Form submission with preventDefault
const form = document.querySelector("#search-form");
form.addEventListener("submit", (event) => {
  event.preventDefault();  // stop page reload
  const query = new FormData(form).get("q");
  searchAPI(query);
});

// Live search with the input event
const searchInput = document.querySelector("#search");
searchInput.addEventListener("input", (event) => {
  console.log("Current value:", event.target.value);
});
            

Event delegation uses one listener on the parent and closest() to find the relevant child. This handles dynamically added items without new listeners. The form handler calls preventDefault to stop the default page reload. The input event fires on every keystroke for live updates.

Try it

  • Markdown Previewer

    This tool uses the input event to update the preview as you type — try it.

  • JSON Formatter

    The format button uses a click event handler — inspect it in DevTools.

Common mistakes

The mistake

Adding a separate event listener to every item in a large list.

The fix

Use event delegation: attach one listener to the parent container and use event.target to determine which child was interacted with. This is more memory-efficient and automatically handles dynamically added items.

The mistake

Forgetting preventDefault on form submit handlers, causing a full page reload.

The fix

Always call event.preventDefault() in a submit event handler if you are handling the form with JavaScript (e.g., via fetch). Without it, the browser performs a traditional form submission and reloads the page.

Related Snippets

Related Cheatsheets

Practice Event Handling

7 exercises

Practice Event Handling

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors