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 Answers6

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/

VisioN
  • 143,310
  • 32
  • 282
  • 281
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

gogic1
  • 111
  • 1
  • 10
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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
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?

Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
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");
});
VisioN
  • 143,310
  • 32
  • 282
  • 281
eg_dac
  • 701
  • 4
  • 14
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/

Michael Aguilar
  • 766
  • 8
  • 16