1

I have two click events on the same element. One of them is a delegated event, and the the other one is not.

$( document ).on( 'click.bar', 'p', function( e ) {

    console.log( 'click.bar', e );

    e.stopImmediatePropagation();

});

$( 'p' ).on( 'click.foo', function( e ) {

    console.log( 'click.foo' );

});

I want to disable the "click.foo" in a specific situation, when "click.bar" is executed. The problem is, that "click.foo" is always called before "click.bar" is called. Any ideas?

Stephan
  • 11
  • 3
  • Maybe this helps https://api.jquery.com/event.stoppropagation/ It will stop propagation above in DOM tree. – Zeeshan Mar 20 '15 at 12:02
  • Unfortunately the stopPropagation function has no effect on delegated events. – Stephan Mar 20 '15 at 12:04
  • 1
    You would need to use event capturing instead of event bubbling – http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing jQuery only supports bubbling event model. – CBroe Mar 20 '15 at 12:42

1 Answers1

0

If you handle both events from $(document), the event.stopImediatePropagation works fine.

You have to register the first event (the one with the event.stopImediatePropagation) first in the script, so it is called first when document is clicked.

$( document ).on( 'click.bar', 'p', function( e ) {

    console.log( 'click.bar', e );

    e.stopImmediatePropagation();

});

$( document ).on( 'click.foo', 'p', function( e ) {

    console.log( 'click.foo' );

});

Other way it won't work because jQuery bubbles the event up (inner to outer), so the event registered in p is triggered first before it reaches the document.

jpenna
  • 8,426
  • 5
  • 28
  • 36