Skip to content Skip to sidebar Skip to footer

Stoppropagation: Element.addeventlistener Vs Onclick Attribute

I'm playing with stopPropagation, adapting code from an MDC doc. Here's the question: Everything works fine if I do what they did and use element.addEVentListener('click', fname).

Solution 1:

Actually, your event acts in the following ways:

Event Fires, Capturing Phase, Bubbling phase, Event has Default Action applied.

Thus, in order to stop propagation you can do the following:

element1.addEventListener('click',fname,true)  // Capturing phase
element1.addEventListener('click',fname,false) // Bubbling phase

fname(event){
  event.stopPropagation();
//event.preventDefault(); is also available here (in both phases I believe)
}

Please note that propagation can only be stopped during the bubbling phase, and only using event handlers in this way allows you to interrupt an event.

As far as I know the tradidtional method of

<divonclick="return fname();">

does not allow this functionality.

Solution 2:

When you do this:

<divonclick="fname();">

You're not assigning fname as the event handler, you're callingfname from within your event handler (which is an anonymous function created for you). So your first parameter is whatever you pass into fname, and in your quoted code, you're not passing anything into it.

You'd want:

<divonclick="fname(event);">

But even that won't be reliable, because it assumes that either the auto-generated anonymous function accepts the event parameter using the name event or that you're using IE or a browser that does IE-like things and you're looking at IE's global window.event property.

The more reliable thing to do is this:

<divonclick="return fname();">

...and have fname return false if it wants to both stop propagation and prevent the browser's default action.

All of this why I strongly advocate always using DOM2 methods (addEventListener, which is attachEvent — with slightly different arguments — on IE prior to IE9) to hook up handlers if you want to do anything interesting in the event (or, 9 times out of 10, even if you don't).


Off-topic: And this whole area is one of the reasons I recommend using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over browser differences for you so you can concentrate on your own work.

Post a Comment for "Stoppropagation: Element.addeventlistener Vs Onclick Attribute"