Kevin
Kevin

Reputation: 33

jQuery click event when an element is inside another element

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?

Upvotes: 3

Views: 3940

Answers (3)

Mukesh Kalgude
Mukesh Kalgude

Reputation: 4844

You can also create this type of event

$(document).on('click','#a>.b',function(){
   var current_id = $(this).attr("id"); 
   alert(current_id);
});

Upvotes: 0

Ilia Choly
Ilia Choly

Reputation: 18557

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/

Upvotes: 5

lonesomeday
lonesomeday

Reputation: 237865

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.

Upvotes: 3

Related Questions