6

If multiple event handlers are attached to same event on the same elements, in which order are they executed?

I have had a look at this which is more specific to click event. this says that standards do not specify anything about order.

So, my question is, in what order events are executed? (that event can be any event may be synchronous or asynchronous)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
hrishikeshp19
  • 8,838
  • 26
  • 78
  • 141

2 Answers2

2

As best I can tell through empirical testing, the click event handlers are executed in the order they were attached to the object. The first one attached is the first one to execute.

Here's a test bed that I ran in Chrome, Firefox, IE9 and Safari and they all executed the event handlers in the order they were initially attached.

Working test bed: http://jsfiddle.net/jfriend00/yTYxV/

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

The order of execution of the event handlers should not matter. I cannot tell for sure but I think that the standard does not specify anything about that. Each implementation is free to choose whatever algorithm fits their flow best.

The event handlers should be independent. An event handler should not depend on another event handler or on the effects of the execution of another handler. An event handler should not even know that other handlers are installed for the same event.

If it does matter for you, then you have a coupling between the handlers. Either the coupling is artificial (for example, some data structure is shared, not because it needs to be shared but because that was the easiest way when the code has been written) and in this case you can remove it, or the coupling shows that the processing that should stay in one handler has been artificially split into two (or more) separate handlers.

Your question, in fact, reveals a problem in the architecture of the application. Solve the problem (make the event handlers independent) and, magically, you won't care any more in which order they are executed. Bonus, your application will be better designed and easier to modify and reason about its behaviour.

axiac
  • 68,258
  • 9
  • 99
  • 134