Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click event when an element is inside another element

Tags:

jquery

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?

like image 958
Kevin Avatar asked Dec 09 '25 18:12

Kevin


2 Answers

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/

like image 68
Ilia Choly Avatar answered Dec 12 '25 12:12

Ilia Choly


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.

like image 30
lonesomeday Avatar answered Dec 12 '25 13:12

lonesomeday