4

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!

frequent
  • 27,643
  • 59
  • 181
  • 333

1 Answers1

6

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Interesting. Let me check (and do is reserved... I replaced my long variable name with something shorter. pardon) – frequent Mar 10 '14 at 16:47
  • @BakedInhalf: If you want the event to stop bubbling (and possibly triggering other event handlers are ancestor elements), call it. If not, don't. – T.J. Crowder Mar 10 '14 at 16:49
  • @T.J.Crowder , So lets say I only want a click/tap on a button, and make sure it's not bubbling - I should use e.stopPropagation() ? – Baked Inhalf Mar 10 '14 at 16:51
  • @BakedInhalf: In your handler for the button, yes; otherwise, the event will propagate to the button's parent, then its parent, etc. to the root. – T.J. Crowder Mar 10 '14 at 17:13