Click event target gives element or it's child, not parent element
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?
Solution 1:
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
Solution 2:
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