• 971-553421531
  • info@efaschool.com
  • Dubai(United Arab Emirates)

JavaScript CurrentTarget Property

JavaScript CurrentTarget Property

The currentTarget property in javascript is read-only property of the Event interface that identifies the current target for the Event, as the event traverses the DOM. It always reffers to the element to which the event handler has been attached, as opposed to the target property, which identifies the element on which the event occurred and which may be its descendant.

Here is an example of how to use the currentTarget property:

JavaScript CurrentTarget Code

        
          const button = document.querySelector('button');
          button.addEventListener("click", function(event){
            console.log(event.currentTarget); //The button element
          });
        
      

In this example, the click event is attached to the button element. When the click event occurs, the currentTarget property of the event object will be the button element.

The currentTarget property is useful during capturing and bubbling. During capturing, the event bubbles up the DOM tree from its target element to its parent elements. During bubbling, the event bubbles down the DOM tree from its target element to its child elements. The currentTarget property alway reffers to the element that the event handler is attached to, regardless of whether the event is currently in the capturing or bubbling phase.

Here is an example of how the currentTarget property can be used during capturing:

JavaScript Capturing

          
            const div = document.querySelector('div');
            div.addEventListener("click", function(event){
              if(event.currentTarget === div){
                console.log("The click event was captured by the div element.");
              }
            });
          
        

In this example, the click event handler is attached to the div element. When the click event occurs on the div element, the currentTarget property of the event object will be the div element, so the if statement will be true and the message will be logged to the console.


Leave a Reply

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