In this post, we will learn on javascript event capturing

Event Capturing:

  • Event capturing refers to the propagation of an event from the outermost element to the innermost element.
  • the event “captures down” the DOM tree.
  • This phase occurs before the bubbling phase.

Event capturing Example in JavaScript:

Consider the following HTML:

<div id="div1">
  <p id="p1">
    <button id="button1">Click me</button>

In this example, we have a button inside a p element which is inside a div element. When we click the button, we want to log the ID of the element that received the event first.

Javascript code:

document.getElementById("button1").addEventListener("click", function(event) {
  console.log("Button clicked");
}, true);

document.getElementById("p1").addEventListener("click", function(event) {
  console.log("Paragraph clicked");
}, true);

document.getElementById("div1").addEventListener("click", function(event) {
  console.log("Div clicked");
}, true);

When we click the button, the following will be logged to the console:

cssCopy codeDiv clicked
Paragraph clicked
Button clicked

This shows that the event started at the outermost element (the div), then captured down to the innermost element (the button). This is why it’s called event capturing.

Note the true argument passed to the addEventListener method. This tells JavaScript to use the capturing phase instead of the bubbling phase.

Thanks for Readding

Leave a Reply

Your email address will not be published. Required fields are marked *