I am having an issue very similar to: \"Jquery \'click\' not firing when icon is on button\" however the resolution for that post is not providing a solution for me, so I th
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.
How bout just checking within the function if the tagname is I, and if it is, getting the parent as your $btn. http://jsfiddle.net/jFIT/qZgYU/3/
$('body').on('click', 'button.vote-button', function() {
var $btn = $(this).prop('tagName').toLowerCase() == "i" ? $(this).parent() : $(this);
console.log(parseInt($btn.data('vote')));
console.log($btn.prop('tagName'));
});
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);
});
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;
}