I've got this HTML element:
<div class="list-group">
<a href="javascript:;" @click="showDetails(notification, $event)" class="list-group-item" v-for="notification in notifications" :key="notification.id">
<h4 class="list-group-item-heading">{{ '{{ notification.title }}' }}</h4>
<p class="list-group-item-text">{{ '{{ notification.created_at|moment }}' }}</p>
</a>
</div>
And this Javascript:
return new Vue({
methods: {
showDetails: function (notification, event) {
this.notification = notification
console.info(event.target)
}
}
}
The problem is that event.target
return the exact element I click. That means it can be the a
element, or one of it's children (h4
or p
).
How do I get the a
element (the element with the @click
handler), even if the user clicks on one of it's children?
Use stopPropagation method, see an example: As said by jQuery Docs: stopPropagation method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
use event.currentTarget
which points to the element that you attached the listener. It does not change as the event bubbles
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
Alternative solution with CSS:
a * {
pointer-events: none;
}
The element is never the target of pointer events; however, pointer events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, pointer events will trigger event listeners on this parent element as appropriate on their way to/from the descendant during the event capture/bubble phases.
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events#Values
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