Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a click on a nested element not bubbling up to it's parent with the click binding?

I have this HTML:

<a href="#" class="action" data-action="foo">
  <h1>Some</h1>
  <p>Text<p>
</a>

and this binding:

$(document).on("click", ".action", function (e) {
  var do = e.target.getAttribute("data-action");
  if (do === undefined || do === null) {
    console.log("error");
  }
});

Strangely if I click on h1 or p, my error logs, while I was expecting the click to bubble up to the link element.

Question:
What is the normal behaviour if elements nested inside an element with a click handler are clicked? Why is my click not bubbling up?

Thanks!

like image 554
frequent Avatar asked Oct 26 '25 09:10

frequent


1 Answers

Strangely if I click on h1 or p, my error logs, while I was expecting the click to bubble up to the link element.

It does (which is why jQuery called your event handler), you're just not looking at that element.

The target property of the event object is the element where the event started (so, the h1 or the p), not the element on which you've hooked the event, the one that the eventhandler currently running is associated with. With jQuery (and DOM2's addEventListener), the element where you've hooked the event is given to you as this (and also as currentTarget on the event object).

So if you change your e.target to this, you'll get the behavior you expect.


Side note: do is a reserved word in JavaScript, you can't use it as a variable name. I'm surprised that code doesn't fail with an error to that effect.

like image 120
T.J. Crowder Avatar answered Oct 28 '25 21:10

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!