Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Prevent parent's event to be triggered when child's event is triggered [duplicate]

Recently I have some problems with jQuery. Let's just say I have elements like this:

<div id="parent1" class="parent">
    <div id="child1" class="children">
        <a href="" id="child_link1" class="child_link"></a>
    </div>
</div>

and I have jQuery function like this:

$(".parent").click(function(){
    alert("parent is clicked");
});

$(".child_link").click(function(){
    alert("child link is clicked");
});

If I click the child_link, parent will be triggered too. How can I create a situation where if I click the child_link, parent won't be triggered?

like image 952
Henry Gunawan Avatar asked Jan 23 '13 11:01

Henry Gunawan


3 Answers

You need to stop propagation on the child click event, like this:

$(".child_link").click(function(e) {
    e.stopPropagation();
    alert("child link is clicked");
});

Example fiddle

like image 192
Rory McCrossan Avatar answered Oct 18 '22 03:10

Rory McCrossan


Event handler for the child should be written like so:

$(".child_link").click(function( event ){
    event.stopPropagation();
    alert("child link is clicked");
});

This will stop event bubbling, and parent's event handler will not get called.

like image 31
Jan Hančič Avatar answered Oct 18 '22 02:10

Jan Hančič


See your event is getting bubbling up to its parent. So here you have to use .stopPropagation();:

$(".child_link").click(function(ev){
  ev.stopPropagation(); //<----------------this stops the event to bubble up
  alert("child link is clicked");
});
like image 44
Jai Avatar answered Oct 18 '22 03:10

Jai