I have a problem with the jQuery click event when an element is inside another element. The code I am using is similar to the following:
<div class="a" id="a">
<a class="b" id="b"></a>
</div>
$(".a,.b").click(function() {
var current_id = $(this).attr("id");
alert(current_id);
...do something...
});
When I click on the tag class="b" it returns the encapsulated class="a" id instead of the id of class="b". How do I code it so that when I click on class="a" or class="b" it returns the correct corresponding id value?
you have to stop it from bubbling.
$(".a,.b").click(function() {
var current_id = $(this).attr("id");
alert(current_id);
// ...do something...
return false; // <-- stop propagation
});
demo: http://jsfiddle.net/Q9njP/
EDIT: better way
$(".a,.b").click(function(event) {
var current_id = event.target.id;
alert(current_id);
// ...do something...
event.stopPropagation();
});
demo: http://jsfiddle.net/xMGgA/1/
You need to use the event target. This is the element where the event originated:
$(".a").click(function(event) {
var current_id = event.target.id;
alert(current_id);
...do something...
});
Note that this is the same as $(event.target).attr('id'), but cleaner and faster, and that I've removed the reference to .b since all events fired on .b will be matched on .a anyway.
See jsFiddle example.
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