Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are event handlers in JavaScript called in order?

If I attach multiple event handlers to a single event on a single DOM element, are the event handlers guaranteed to be called in the order they were added? Or should I not rely on this behavior?

like image 719
Sasha Chedygov Avatar asked Apr 24 '10 20:04

Sasha Chedygov


People also ask

In what order are event handler functions executed?

1) Currently they are executed in the order that the implementation of the specific event dictates - since you can implement your own add/remove methods for events. 2) When using the default event implementation via multi-cast delegates, the order is in fact required by specifications.

How does event handlers work JavaScript?

JavaScript Event HandlersEvent handlers can be used to handle and verify user input, user actions, and browser actions: Things that should be done every time a page loads. Things that should be done when the page is closed. Action that should be performed when a user clicks a button.

Which event listener fires first?

Event capturing the event handler of element1 fires first, the event handler of element2 fires last.


1 Answers

This has been changed with DOM3! While the DOM level 2 events specification did state

When the event reaches the target, any event listeners registered on the EventTarget are triggered. 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 current DOM level 3 events specification does now state

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. […]

Finally, the implementation MUST process all candidate event handlers in order […]

However, I can't find a reference to this behaviour in the DOM 4 draft any more.

like image 195
Bergi Avatar answered Oct 09 '22 19:10

Bergi