stopPropagation: element.addEventListener vs onclick attribute

Nathan picture Nathan · Apr 18, 2011 · Viewed 18k times · Source

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).
But, when I try to attach the function with the element's onclick attribute ( <div onclick="fname();"> ), propagation does not stop.
And if I use <div onclick="function(ev) {fname();}">, fname() isn't called at all (I also tried passing fname(ev) with the same results).

Ideas anyone? Let me know if you need to see the code.

Answer

GAgnew picture GAgnew · Apr 18, 2011

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

<div onclick="return fname();">

does not allow this functionality.