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

Asked

Viewed 280 times

5

What’s 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" />

1 answer

1

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

event.target is the element that triggered the event. Imagine that inside the element "meuId" there are other elements, that if clicked, trigger the event of the father "meuId", event.target will be that element.

event.currentTarget is the same as this. In case you click on a "child" element of "meuId", event.target it will be the element that triggered the event, and event.currentTarget will be the "father".

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 "father" , this, event.target and event.currentTarget will be equal if you click on the div "child", event.target will be the son.

See a functional example here: https://jsfiddle.net/p08fh103/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.