The Order of Multiple Event Listeners

As a formatted comment of @T.J. Crowder's answer, I tested which modern browsers actually trigger the listeners in registration order.

2016-10-06: The results are that all following browsers do: chrome 53, firefox 49, safari 9, opera 40, ie 11 and edge 13 via virtualbox on mac host.

The code of my test can be found here: https://github.com/lingtalfi/browsers-behaviours/blob/master/listeners-execution-order/listeners.md


Prototype relies on the browser's underlying firing mechanism for order (not all libraries do, see below). The order in which event handlers are fired was not guaranteed by the DOM events stuff originally. From the DOM2 Events specification:

Although all EventListeners on the EventTarget are guaranteed to be triggered by any event which is received by that EventTarget, no specification is made as to the order in which they will receive the event with regards to the other EventListeners on the EventTarget.

The vast majority of browser implementations (Chrome, Firefox, Opera, etc.), including IE9, fire the handlers in the order in which they were attached. IE8 and earlier do it the other way around.

The newer DOM3 event spec, still a work in progress, introduces the requirement that they be fired in order of registration (what most browsers do):

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.

...which is probably part of why IE9 does that now (IE9 markedly improved Microsoft's support for the events standards, adding addEventListener, etc.).

Some JavaScript libraries (jQuery for instance) do guarantee the order regardless of the browser, by attaching only a single handler per event per element and maintaining their own list of user code handlers to fire.