Difference between currentTarget, delegateTarget and target in JQuery event

5

I have this simple script that captures a one-button event with jQuery:

$(function() {
  $('#myButton').click(function(evt) {
    console.log(evt);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" type="button">
  Enviar
</button>

The variable evt when displayed in the console has several properties called:

  • target
  • currentTarget
  • delegateTarget
  • relatedTarget

All of them except relatedTarget refer to the same object, the button that generated the event. Does anyone know what the difference between them is? If they all point to the same object, why does jQuery use them?

    
asked by devconcept 24.12.2015 в 19:44
source

2 answers

8

target : Refers to the object element on which the event has been assigned. Taking into account a structure like the following:

<div class="box">
    <span>Texto aquí</span>
</div>

and the following code:

$('.box').click(...);

By giving clic in span the event is activated because it is due to the bubble effect (more information in: Bubbling and JQuery events - Java architecture ), at that time the current goal of the click ( currentTarget ) is span , but the goal as such ( target ) is div .

The relatedTarget acts in the same way but is available for objects that delegate your event as we see it below:

<div class="box">
    <span>Texto aquí</span>
</div>

the jQuery code would be:

$('.box').on('click', 'span', function(evt){...});

The delegateTarget is the div.box . It is important to mention that for non-delegated elements: delegateTarget will always be equal to currentTarget .

    
answered by 24.12.2015 / 19:53
source
3

Well according to the MDN (Mozilla developer Network) It says the following:

event.target : The Element of the DOM, which has triggered an event.

event.currentTarget : Always refers to the event handler element (Event Handler) that has been attached to a event.target specific, this Identifies the element in which the event occurred.

event.relatedTarget : Identify a secondary target for the event, this can be seen when you work with the Mouse events.

event.delegateTarget : Contains the element that is in progress of execution, this is used when working with .on() to know who called the event.

Resources

    
answered by 24.12.2015 в 20:21