JQuery: how to stop a child onclick event while still raising the parent onclick event

I wonder how I can stop the onclick child event while still raising the onclick parent event. For example, the following structure:

<div id="parent"> <div id="child1"></div> <div id="child2"></div> <div id="child3"></div> </div> 

if I press "child1", for example, the onclick event for "child1" will not be fired, however the onclick event for "parent" will still be fired.

Thank you very much!

+4
source share
4 answers

Can you just pass click parent?

 $('.child1').click(function(e){ e.preventDefault(); $(this).parent('#parent').trigger('click'); }); 

When you press .child1, this will prevent the default action, and then trigger a click for parent child1 with id #parent.

Actually - perhaps ignore the above - in accordance with the comment below, it can cause bubbles. All you really need to do is use e.stopPropagation(); .

I created jsfiddle , showing that although child1 has a click function associated with it, it is ignored and therefore the parent click only receives.

+2
source

The easiest way to do this is to cancel the child event handler.

 $('#child1').unbind('click'); 
+2
source

Here is a container to solve the problem above. Please check the demo link once.

Demo: http://codebins.com/bin/4ldqp7l

HTML

 <div id="parent"> <div id="child1"> Child-1 </div> <div id="child2"> Child-2 </div> <div id="child3"> Child-3 </div> </div> 

JQuery

 $(function() { $("#parent").click(function() { alert("Parent has been clicked too...!"); }); $("#child1").click(function(e) { e.stopPropagation(); alert("Child-1 has been clicked...!"); }); $("#child2").click(function() { alert("Child-2 has been clicked...!"); }); $("#child3").click(function() { alert("Child-3 has been clicked...!"); }); }); 

CSS

 #parent{ padding:5px; background:#a34477; width:140px; text-align:center; padding:10px; } #parent div{ border:1px solid #2211a4; background:#a3a5dc; width:100px; text-align:center; font-size:14px; margin-left:10px; margin-top:3px; } 

Demo: http://codebins.com/bin/4ldqp7l

+2
source

Do you mean:

 $('#parent').on('click', function(e) { if( e.target !== this ) { return; } }); 
+1
source

Source: https://habr.com/ru/post/1432437/


All Articles