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?
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
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.
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");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With