3

If I register two event listeners to the same event target. Which event handler will be called first?

Example:

document.addEventListener("click", function() {
    // do something 1
}, true); // using the capturing phase

document.addEventListener("click", function() {
    // do something 2
}, true); // using the capturing phase

I do not found my answer in the w3c specification.

DOM-Level-3-Events

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • possible duplicate of [Are event handlers in JavaScript called in order?](http://stackoverflow.com/questions/2706109/are-event-handlers-in-javascript-called-in-order) – James Montagne Feb 01 '13 at 21:56
  • Try it in different browsers http://jsbin.com/azuzef/1/edit , Google Chrome and Firefox seem to be in order of listener added. – Paul S. Feb 01 '13 at 21:58
  • 2
    The [HTML5 spec](http://www.w3.org/TR/DOM-Level-3-Events/#event-flow) says: "the list of all event listeners that have been registered on the current target in their order of registration" and "the implementation must process all candidate event handlers in order". – pimvdb Feb 01 '13 at 22:01

1 Answers1

1

Bold emphasis added to answer the question (via the w3c specification: http://www.w3.org/TR/DOM-Level-3-Events/#event-phase)

First, the implementation must determine the current target. This must be the next pending event target in the partial propagation path, starting with the first. From the perspective of an event listener this must be the event target the listener has been registered on.

Next, the implementation must determine the current target's candidate event listeners. This must be the list of all event listeners that have been registered on the current target in their order of registration. [HTML5] defines the ordering of listeners registered through event handler attributes. Once determined, the candidate event listeners must not be changed; adding or removing listeners does not affect the current target's candidate event listeners.

Finally, the implementation must process all candidate event handlers in order and trigger each handler if all the following conditions are met...

I have personally always relied on this behavior, and I have not seen a modern browser behave differently than the spec describes.

wxactly
  • 2,400
  • 1
  • 26
  • 42