How to stop event propagation when using a delegate?

When I use .bind to bind an event to a child and a parent, the child event can stop the propogation event and return false; But when I use a delegate, return false; does not stop the spread of events.

http://jsfiddle.net/J3EAQ/

HTML:

<div class="parent"> <div class="child"></div> <div class="child"></div> </div> 

JS:

 $('.parent').delegate('.child','click',function(e){ alert('child click'); return false; }); $('.parent').bind('click',function(e){ alert('parent click'); }); 
+7
source share
6 answers

e.stopPropagation() will not work in this case. Use e.stopImmediatePropagation () instead . Here fiddle

+8
source

Why two click handlers when you have them:

 $( '.parent' ).click(function ( e ) { if ( $( e.target ).is( '.child' ) ) { alert( 'child click' ); } else { alert( 'parent click' ); } }); 

Live demo: http://jsfiddle.net/J3EAQ/2/


A generalization of this template:

 $( element ).click(function ( e ) { if ( e.target === this ) { // this element was clicked directly } else { // this element was NOT clicked directly // a descendant of this element was clicked } }); 

Split handlers?

 $( '.parent' ).click(function ( e ) { if ( this ==== e.target ) { parentClicked.call( e.target, e ); } else { childClicked.call( e.target, e ); } }); function childClicked( e ) { // child click handler } function parentClicked( e ) { // parent click handler } 
+4
source

You should use e.stopPropagation() to prevent the spread, and not by returning false.

return false technically two things; 1) prevent the default action; and 2) stop the distribution. Try switching to a method call on e and see if this fixes your problem.

+1
source

You can always use e.stopPropagation()

0
source

What worked for me was to check the name of the click target class in the click handler that you do not want to trigger with another click event. Something like that.

  if(e.target.className.toString().indexOf("product-row") > -1){ // Only do stuff if the correct element was clicked } 
0
source

your event does not multiply. you bind the click handler to .parent and you click on .parent

-one
source

All Articles