Sobes.tech
Middle+

What is event bubbling and capturing in JavaScript?

sobes.tech AI

Answer from AI

In JavaScript, event handling in the DOM occurs in three stages: capturing, target, and bubbling.

Capturing — the event first passes from the root of the document down through the DOM tree to the target element. At this stage, handlers with the parameter capture: true can intercept the event.

Target phase — the event reaches the element where the action occurred.

Bubbling — after the target phase, the event bubbles back up the DOM tree to the root, invoking handlers with capture: false (default).

Example:

const parent = document.getElementById('parent');
const child = document.getElementById('child');

parent.addEventListener('click', () => console.log('parent capture'), true); // capturing
parent.addEventListener('click', () => console.log('parent bubble')); // bubbling
child.addEventListener('click', () => console.log('child target'));

// When clicking on child, the call order is:
// 1. parent capture
// 2. child target
// 3. parent bubble

Thus, bubbling allows handling events on parent elements without needing to attach handlers to each child element.