addEventListener and the Event Object

Runs a function in response to a browser event, receiving an event object describing what happened and how to control the default behavior.

                element.addEventListener(type, handler)
              

Purpose

addEventListener registers a function to run whenever a given event fires on an element — a click, a keypress, a form submission, and many others. The handler receives an event object describing what happened.

Syntax

const button = document.querySelector('#save-button');

button.addEventListener('click', function (event) {
  console.log('Clicked:', event.target);
  event.preventDefault();
});

Behavior notes

  • event.target is the exact element the event originated on — for a click inside a button that contains an icon and text, target could be the icon, not the button, depending on exactly where the click landed.
  • event.preventDefault() stops the browser’s default action for that event (a link navigating, a form submitting) without stopping the event from continuing to propagate.
  • Events bubble: after firing on target, the same event fires again on each ancestor element in turn, up to document. This underlies event delegation (covered in the Intermediate tier), which attaches one listener to a parent instead of one per child.
  • removeEventListener requires passing the exact same function reference used in addEventListener — an inline anonymous function can’t be removed later, since there’s no reference to it.

Common mistakes

  • Assuming event.target is always the element the listener was attached to — it’s whichever element the event actually originated on, which can be a descendant.
  • Forgetting preventDefault() on a form’s submit event, causing an unwanted full-page reload.
  • Attaching an anonymous function when the listener will need to be removed later.

Runtime notes

Part of the DOM standard — browser-only. Node has its own separate EventEmitter pattern for similar behavior server-side, covered in the Intermediate tier.

Taught in these lessons

Related reference