When I use .bind to bind event on child and parent, child event can stop event propogation with return false; But when I use delegate, return false; does not stop event prop
e.stopPropagation()
won't work in this case. Use e.stopImmediatePropagation() instead. Here's a fiddle
your event is not being propagated. you are binding a click handler to the .parent, and you are clicking on .parent
What worked for me was to check the class name of the click target in the click handler that you don't want to get triggered by other click event. Something like this.
if(e.target.className.toString().indexOf("product-row") > -1){
// Only do stuff if the correct element was clicked
}
You should be using e.stopPropagation()
to prevent the propagation, not by returning false.
return false
is technically two things; 1) prevent the default action, and 2) stop propagation. Try switching to the method invocation on e
and see if that fixes your problem.
You can always use e.stopPropagation()
Why two click handlers when you can have one:
$( '.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 pattern:
$( 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
}
});
Separate 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
}