Language: EN

javascript-eventos-en-el-dom

What are events in the DOM in JavaScript

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

Events are a fundamental part of JavaScript, the language itself. We have already seen that we can use it in both the browser and at runtime (like NodeJS).

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

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

So, we are going to dedicate a section to talk about events, specifically events in the browser. Let’s go for it 👇.

Common Types of Events

The browser provides us with a lot of events, of different types. Some of them are,

CategoryEvents
Windowload, resize, scroll, unload
LoadingDOMContentLoaded, load
Mouseclick, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout
Keyboardkeydown, keypress, keyup
Formsubmit, change, focus, blur, input

Event Handlers

To interact with events, we need event handlers, which are functions that we define to execute 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]);

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 attached.
bubblesIndicates whether the event bubbles 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)
});

Event Methods

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

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

Event Propagation

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

  1. Capturing phase: The event starts at the root document and travels down to the event target.
  2. Bubbling phase: The event travels from the event target back up to the root document.