Click event on button is sending an icon as the target?
update this because $(event.target)
is not always button
for this you have to use ternary operator as suggested or replace $(event.target)
with $(this)
which is always button
in the context of selector:
function sendVote(event) {
event.stopPropagation();
var $btn = $(event.target).is('button') ? $(event.target) : $(event.target).parent();
console.log(parseInt($btn.data('vote')));
console.log($btn.prop('tagName'));
}
$(function () {
$('body').on('click','button.vote-button', sendVote);
});
Demo fiddle
or with $(this)
which is always button
because the event is bound to it and if you click on any child of it then event
will bubble up to the dom tree and event bound to button gets executed:
function sendVote(event) {
var $btn = $(this); // <-----------------change just here
console.log(parseInt($btn.data('vote')));
console.log($btn.prop('tagName'));
}
Simple CSS solution:
button > * {
pointer-events: none;
}
It's caused by event propagation. You click on the icon, which is inside the button, so the click
event propagates up through the DOM from the icon, to the button, all the way up to the document. This results in your click
event handler code being executed.
If the issue is that you just want the reference to the button every time that code runs, but you still want it to trigger when you click on the icon instead of the text, you just need to use this
rather than event.target
:
var $btn = $(this);
...
jQuery will make sure that this
always refers to the button, even if the actual event.target
element is an element inside it.
Use event.currentTarget
which is always the object listening for the event; event.target
is the actual target that received the event which is not what you want in this case since it could be the icon.
With event.currentTarget
if the user clicks on the icon, it'll bubble the event up to the object listener which is the button in your case. If the user clicks the button it'll still work because again the object listener is your button.