Reputation: 1391
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 propagation.
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');
});
Upvotes: 7
Views: 4450
Reputation: 2474
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
}
Upvotes: 0
Reputation: 185923
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
}
Upvotes: 4
Reputation: 25776
e.stopPropagation()
won't work in this case. Use e.stopImmediatePropagation() instead. Here's a fiddle
Upvotes: 8
Reputation: 3532
your event is not being propagated. you are binding a click handler to the .parent, and you are clicking on .parent
Upvotes: -1
Reputation: 41236
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.
Upvotes: 1