javascript-eventos-en-el-dom

What are events in the DOM in JavaScript

  • 3 min

An event in JavaScript is a specific action or occurrence to which we may want to detect and act when it happens.

Events are inherent to JavaScript, to the language itself. We have already seen that we can use it both in the browser and in runtime (like NodeJS).

However, events are most frequently used in the browser. This is because they allow us to react to events that commonly occur in the frontend.

Some examples are user actions (like clicking a button, or typing in an input), or actions of the browser itself (like finishing loading a page).

So we are going to dedicate a section to talking about events, but specifically events in the browser. Let’s get to it 👇.

Event handlers

To interact with events we need event handlers, which are functions we define that will be executed in response to these occurrences.

To associate a function with an event we use the addEventListener method. The basic syntax is:

element.addEventListener(event, handler, [options]);
Copied!

Event properties

Event objects in JavaScript provide information about the event that occurred. These objects are automatically passed to event handlers and have useful properties. Some of them are:

PropertyDescription
typeThe type of event (like 'click', 'keydown').
targetThe element that triggered the event.
currentTargetThe element to which the event handler has been added.
bubblesIndicates whether the event bubbles up through the DOM.
cancelableIndicates whether the event can be canceled.
button.addEventListener('click', (event) => {
  console.log(event.type);         // 'click'
  console.log(event.target);       // The clicked button
  event.preventDefault();          // Prevents the default action (if applicable)
});
Copied!

Event methods

Event objects also provide useful methods that allow controlling how the event behaves. Some of them are:

MethodDescription
preventDefault()Prevents the default action of the event.
stopPropagation()Stops the propagation of the event to other phases.
button.addEventListener('click', (event) => {
  event.preventDefault();          // Prevents the default action (if applicable)
  event.stopPropagation();         // Stops the event from propagating
});
Copied!

Event propagation

Event propagation refers to the process by which an event moves through the DOM element tree, from the event origin to the final target. This process can follow two main phases:

  1. Capturing phase: The event starts at the document root and travels towards the event target.
  2. Bubbling phase: The event travels from the event target towards the document root.