event.target.id VS event.currentTarget.id VS this.id

I have this sample code provided below:

HTML:

<button id = '33' class = "clickme">Click here</button>

JS:

$(document).on("click",".clickme",function(event){ 
    var eti = event.target.id;
    var eci = event.currentTarget.id;
    var ti = this.id;

    alert ("1: " + eti + "   2: " + eci + "   3: " + ti);
}

These 3 events, alerts the same value and I thought it also plays the same role but not in this link I found in SO: jquery function(event) event.target.id is blank when clicking linked text.

Now my question is:

1.) What is the difference between using: event.target.id, event.currentTarget.id and this.id?

2.) When should I use event.target.id, event.currentTarget.id and this.id?

3.) And which works better among these three?

Does anybody have an idea and explanation why?

Enquirer: Makudex

||

Solution #1:

Try this example

<div id="maindiv" onclick="callback(event, this);">
  <span id="span" onclick="callback(event, this);"> SPan</span>
  <p id="p" onclick="callback(event, this);">This is p </p>
</div>

function callback(e, thisObj) {
       console.log('this=", thisObj.id);
       console.log("target=", e.target.id);
       console.log("currentTarget=", e.currentTarget.id);
    }

event.target is what dispatches the event.
ex: if you click on p event.target will be p but event.currentTarget will be p when callback of p will be called event.currentTarget will be maindiv when callback will be called cause of event bubbling.

`this` refers to `event.currentTarget`

See this one for details
https://developer.mozilla.org/en-US/docs/Web/API/Event/Comparison_of_Event_Targets

Here is a same question i think see this one
Difference between e.target and e.currentTarget

Respondent: intekhab

Solution #2:

event.target.id and this.id are the same, in the first one you are accessing the target from the event object in the second you are accessing it through jquery object.

event.currentTarget.id

The current DOM element within the event bubbling phase.

As per it”s documentation.

In JavaScript, events bubble. This means that an event propagates through the ancestors of the element the event fired on.

You can check this fiddle and check various event properties.

Respondent: KAD

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.