8

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Makudex
  • 1,042
  • 4
  • 15
  • 40

2 Answers2

8

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

Community
  • 1
  • 1
intekhab
  • 1,566
  • 1
  • 13
  • 19
0

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.

KAD
  • 10,972
  • 4
  • 31
  • 73
  • It is more helpful if you answer the question (at least in brief) than sending the reader to links (that might get outdated as time goes on) – BjornW Sep 26 '22 at 09:37