Skip to main content

Making pages interactive

An event is something that happens on the page — a click, a key press, a form submission, a mouse hover. Event listeners let you run code when these events occur.
That’s the core pattern: select an element, call addEventListener, pass the event name and a function to run.

addEventListener()

You can attach multiple listeners to the same element and event. They all fire in the order they were added.

Common events

Practical examples

The event object

Every event handler receives an event object with details about what happened:

Key properties

event.target — the most useful property

event.target tells you exactly which element was interacted with:

event.preventDefault() — stop default behavior

Some elements have built-in behaviors. preventDefault() stops them:
Forms reload the page on submit by default. You’ll almost always want e.preventDefault() when handling forms with JavaScript. This is the single most common gotcha in form handling.

Event delegation

Instead of adding a listener to every list item, add one listener to the parent and check event.target:
Benefits of event delegation:
  • Works for elements added after the listener is set up (dynamically created elements)
  • One listener instead of hundreds — better performance
  • No need to re-attach listeners when the list changes
element.closest(selector) walks up the DOM tree from the clicked element and returns the first ancestor matching the selector. It’s essential for event delegation — it finds the container you care about, even if the user clicked a child element inside it.

Removing event listeners

To remove a listener, you need a reference to the same function:

One-time listeners

What’s next?

You can handle clicks and keyboard events. Let’s put it all together with the most common interactive element — forms.

Form handling

Get form values, validate input, and handle submissions