what is the difference of this, event.target and event.currentTarget in the scope of an event?

2

What is the difference between this, event.target and event.currentTarget in the scope of an event?

var elem = document.getElementById("meuId");
elem.addEventListener("click", function (event) {
  console.log(this.id, event.target.id, event.currentTarget.id);
}); 
<input id="meuId" type="button" value="Click Me" />
    
asked by anonymous 26.10.2016 / 17:06

1 answer

1

this is the very element that has the event associating, in your case, the element with "myId".

event.target is the element that fired the event. Imagine that inside the element "myId" there are other elements, which if clicked, trigger the event of the "myId" parent, event.target will be this element.

event.currentTarget is the same as this . In the case of clicking on a "child" element of "myId", event.target will be the element that fired the event, and event.currentTarget will be the "parent".

To illustrate, see the code below:

<div class="pai" id="pai">
  <div class="filho" id="filho"></div>
</div>


$( ".pai" ).click(function(event) {
 // some code
});

Here, if you click on the div "parent", this , event.target and event.currentTarget will be the same, if you click on the div "child", event.target will be the child.

See a working example here: link

    
26.10.2016 / 18:40