Mark As Completed Discussion

Event Propagation

When an event occurs on an element, such as a button click, the event can have an impact on other elements as well. This concept is known as event propagation.

There are two types of event propagation in JavaScript:

  • Bubbling: In the bubbling phase, the event starts from the innermost element and then propagates up to the outermost element.
  • Capturing: In the capturing phase, the event starts from the outermost element and then propagates down to the innermost element.

By default, when an event is triggered on an element, it goes through both the capturing and bubbling phases.

Let's take an example to understand event propagation better. Imagine we have a container element with a button inside it. If we click on the button, the click event will first trigger on the button itself, then on the container element, and finally on the document.

Here's an example code snippet that demonstrates event propagation:

JAVASCRIPT
1const container = document.querySelector('.container');
2const button = document.querySelector('.button');
3
4function handleClick(event) {
5  console.log(event.target.tagName);
6}
7
8container.addEventListener('click', handleClick);
9button.addEventListener('click', handleClick);
10document.addEventListener('click', handleClick);

When you run this code and click on the button, you will see that the event is logged in the console three times: first for the button, then for the container, and finally for the document. This demonstrates the bubbling phase of event propagation.

If you want to stop the event propagation during the bubbling phase, you can use the stopPropagation() method on the event object. For example:

JAVASCRIPT
1function handleClick(event) {
2  event.stopPropagation();
3  console.log(event.target.tagName);
4}

On the other hand, if you want to handle the event during the capturing phase, you can set the third parameter of the addEventListener() method to true. For example:

JAVASCRIPT
1container.addEventListener('click', handleClick, true);

Understanding event propagation is essential when it comes to handling events effectively in your web applications. It allows you to control how events are handled and make the most out of event handling functionality.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment