Search code examples
javascriptjqueryjquery-eventsevent-delegation

Getting the target of the current bubbling phase when using event delegation


I have a div that contains some buttons and I want to attach an event listener to the div that listens for events that bubble up from the buttons inside of it.

The problem I am running into is that the value of event.currentTarget does not appear to match what the docs say it should.

Consider the following code:

$('.container').on('click', '.myButton', function(event) {
  console.log("event.currentTarget:");
  console.log(event.currentTarget);

  console.log("event.target: ");
  console.log(event.target);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="container">
  <button class="myButton">Click Me</button>
</div>

I am using jquery 1.8.3

event.currentTarget should be the container div, but it is being set to the button inside it instead.

How can I get around this. Is this a known bug or am I doing something wrong?


Solution

  • I think it is working as it is supposed to.

    In the mentioned case, event is directly attached to the button, hence currentTarget and target will always be the same.

    $('.container').on('click', '.myButton', function(event) {}); does not mean that the event is attached to the div. It is just delegating the event. Meaning, the event will bubble up only till .container and the event is still attached ONLY to .myButton

    Case 1: If an event is attached to the div

    1. if the button is clicked then the currentTarget would be button and target would be the div.
    2. if div is clicked currentTarget would be div and target would also be div

    Example

    $('.container').on('click', function(event) {
      console.log(event.currentTarget);
      console.log(event.target);
    });
    div{
      border: 1px solid;
      width: 150px;
      height: 150px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <div class="container">
      <button class="myButton">Click Me</button>
      Click me
    </div>

    Case 2: (Your case) If event is attached to button then currentTarget and target would be button always

    $('.container').on('click','.myButton', function(event) {
      console.log(event.currentTarget);
      console.log(event.target);
    });
    div{
      border: 1px solid;
      width: 150px;
      height: 150px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <div class="container">
      <button class="myButton">Click Me</button>
      Click me
    </div>