0

I'm trying to override a click handler by intercepting the event in an inline handler and stopping propagation (propogation disabling code taken from here).

The following code not only doesn't stop the propagation, it's not even firing the inline handler. I can't tell what's wrong.

fiddle: http://jsfiddle.net/trKN4/3/

HTML:

<a onclick='stopIt(event);'>do it</a>​

JS:

function disableEventPropagation(event)
{
   if (event.stopPropagation){
       event.stopPropagation();
   }
   else if(window.event){
      window.event.cancelBubble=true;
   }
}

function stopIt(event) {
    disableEventPropagation(event);
    alert('dont do it');
}


$(function() {

    $('a').click(function(e){
        alert('im doing it');
    });                   

});
Community
  • 1
  • 1
Yarin
  • 173,523
  • 149
  • 402
  • 512

1 Answers1

1

It's not firing the inline function because jsFiddle is wrapping all your code in an onload handler, taking it out of the reachable scope of the handler.

Choose a no wrap option from the menu on the left.

DEMO: http://jsfiddle.net/trKN4/4/

enter image description here

  • @Yarin: It does stop propagation. You've placed both handlers on the same element, so neither handler is a *result* of propagation. Put the jQuery handler on the `'body'`, and you'll see it work. http://jsfiddle.net/trKN4/12/ –  Jun 05 '12 at 14:28
  • Got it, but now im confused- What's the proper way to undo/prevent a non-inline handler from receiving the event? – Yarin Jun 05 '12 at 14:30
  • @Yarin: Depends on the situation, but if you don't control the non-inline handler, I don't know that it's possible. –  Jun 05 '12 at 14:32
  • It is, just figured out- stopImmediatePropogation()- see http://jsfiddle.net/trKN4/13/ (Need to figure out solution for the cancelBubble part..) – Yarin Jun 05 '12 at 14:33
  • @Yarin: Yeah, I'm guessing browser support will be the tough part. –  Jun 05 '12 at 14:38
  • OK, aparently *jquery* stopPropogation/stopImmediatePropogation *does* work cross browser, so this plus your answer make a solution. Thanks – Yarin Jun 05 '12 at 20:42
  • @Yarin: Yes, jQuery's does. I don't think it'll work on native `event` objects in all browsers, but maybe I'm wrong. Anyway, glad you got it working. –  Jun 05 '12 at 21:06