codez
codez

Reputation: 1391

How to stop event propagation when using delegate?

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.

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');
});

Upvotes: 7

Views: 4450

Answers (6)

Jack Vial
Jack Vial

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

Šime Vidas
Šime Vidas

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

aziz punjani
aziz punjani

Reputation: 25776

e.stopPropagation() won't work in this case. Use e.stopImmediatePropagation() instead. Here's a fiddle

Upvotes: 8

Einacio
Einacio

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

Mike C
Mike C

Reputation: 3117

You can always use e.stopPropagation()

Upvotes: 0

Tejs
Tejs

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

Related Questions