JQuery Prevent parent event from triggering a child event

I recently had some problems with jQuery. Let's say I have these elements:

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

and I have a jQuery function as follows:

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

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

If I click on child_link, the parent will also be launched. How to create a situation where, if I click on child_link, the parent will not be launched?

+5
source share
3 answers

You need to stop propagating on the child click event, for example:

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

Script example

+9
source

An event handler for a child should be written as follows:

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

This will stop the bubbling event , and the parent event handler will not be called.

+4
source

, . , .stopPropagation();:

$(".child_link").click(function(ev){
  ev.stopPropagation(); //<----------------this stops the event to bubble up
  alert("child link is clicked");
});
+4
source

All Articles