Computer >> Computer tutorials >  >> Programming >> Javascript

What is Event Capturing in JavaScript?


Event Capturing

Event capturing is the event starts from top element to the target element. It is the opposite of Event bubbling, which starts from target element to the top element.

Code Elaboration

In the following code, in body section three div elements are taken and a style got applied so as to make them nested.

  • Add a event handler to each of the div tags using addEventListener().
  • Make sure that here the event is "click" event.
  • The addEventListener() method accepts 3 parameters.

             a) The event it is going to access, here it is click event.  

             b) An event handler function so as to display alert messages.

             c) The third parameter is called phase. In this parameter if we keep true then the event capturing will be                           enabled.If we keep false then event bubbling will be enabled.  

  • The event handler function, which is used to display alert boxes, will use getAttribute() to get the id value of the div element which got clicked.
  • When we click on the inner most nested tag div3, since event capturing got enabled here, the alert messages starts from top div1 tag to the target tag div3.
  • When we click on the div2 tag, then alert boxes will display from top div1 tag to target tag div2.

Example

<html>
<head>
<style>
   .divstyle{
      display:table-cell;
      border: 2px solid black;
      padding: 20px;
      text-align: center;
   }
</style>
</head>
<body>
   <div id = "div1" class="divstyle">
   div1
   <div id = "div2" class="divstyle">
   div2
   <div id = "div3" class="divstyle">
   div3
<script>
   var divs = document.getElementsByTagName("div");
   for(var i = 0; i<divs.length; i++){
      divs[i].addEventListener("click",clickhandler,true );
   }
   function clickhandler() {
      alert(this.getAttribute("id") + "event got handled");
   }
</script>
</body>
</html>

On executing the above program we get the following image on the screen

What is Event Capturing in JavaScript?

On clicking the above div3(target element) we get the following as output

output

What is Event Capturing in JavaScript?
On clicking ok of the above div1 alert box we get the following div2 alert box opened

What is Event Capturing in JavaScript?
On clicking ok of the above div2 alert box we get the following div3 alert box opened.

What is Event Capturing in JavaScript?