3

I've similar to this:

<ul>
<li class="parent">
<div class="child"></div>
</li>
</ul>

And I've two on click triggers.

$(document).on("click", ".parent", function(){
console.dir("parent clicked");
});

$(document).on("click", ".child", function(){
console.dir("child clicked");
});

If I click child, parent is also clicked! How do i avoid this?

http://jsfiddle.net/Vd2GA/

6 Answers 6

5

Use either return false or e.stopPropagation() in child click event handler:

$(document).on("click", ".child", function(e) {
    console.dir("child clicked");
    return false;  // e.stopPropagation();
});

DEMO: http://jsfiddle.net/Vd2GA/1/

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

Comments

1
 $(document).on("click", ".parent", function(e){
     e.stopPropagation();
    console.dir("parent clicked");
    });

    $(document).on("click", ".child", function(e){
        e.stopPropagation();
    console.dir("child clicked");
    });

should do

Comments

0

Prevent the propagation of event from the child.

 $(document).on("click", ".parent", function () {
     console.dir("parent clicked");
 });

 $(document).on("click", ".child", function (e) {
     console.dir("child clicked");
     e.stopPropagation();
 });

Demo: Fiddle

Note: this technique is possible here only because jQuery does some behind the scene magic when event delegation is used else since both the handlers are registered to document object this cannot be done

Comments

0

Use event.stopPropagation

fiddle Demo

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

 $(document).on("click", ".child", function (e) {
     e.stopPropagation();
     console.dir("child clicked");
 });

Read What is event bubbling and capturing?

Comments

0

Updated the fiddle here: http://jsfiddle.net/Vd2GA/2/.

$(document).on("click", ".parent", function(){
    console.dir("parent clicked");
});

$(document).on("click", ".child", function(e){
    e.stopPropagation();
    console.dir("child clicked");
});

Comments

0

or you can use this condition if you need to be specific

 $(document).on("click", ".parent", function(e){
   if (e.target==this)
    console.dir("parent clicked");
 });

http://jsfiddle.net/Vd2GA/4/

Comments

Your Answer

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