3

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?

3 Answers 3

5

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/

Sign up to request clarification or add additional context in comments.

4 Comments

You should better use event.stopPropagation().
@FelixKling in the question he wasn't using the event parameter. I just gave a working example with the least amount of changes. You are definitively correct though.
'return false;' worked. Thank you. @FelixKling how would event.stopPropagation() work?
@Kevin: have a look at the second example in this answer... the difference is that return false also prevents the default action of the browser which is not necessarily desired. stopPropagation is more expressive as well.
3

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.

3 Comments

@ManseUK That doesn't do anything because you haven't added event as a parameter.
But yes, @FloydThreepwood, it would fire twice. The handler should only be on the parent element, although whether this is the correct solution would depend on the actual real-world situation.
@ManseUK Yes, but it's an unnecessary change, and a bad one unless it's necessary. My change is probably the nicest solution for the abstract case.
0

You can also create this type of event

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.