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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With