What order of precedence are events handled in JavaScript?
Here are the events in alphabetical order...
What order are they handled out of the event queue?
The precedence is not first-in-first-out (FIFO) or so I believe.
The event journey starts at the Document, moves down to the HTML element, moves to the Body element, and finally gets to the Button element. The event then bubbles back up to Document, moving again through the Body element and HTML element on its way up.
Event capturing the event handler of element1 fires first, the event handler of element2 fires last.
That is: for a click on <td> the event first goes through the ancestors chain down to the element (capturing phase), then it reaches the target and triggers there (target phase), and then it goes up (bubbling phase), calling handlers on its way.
This was not, so far as i know, explicitly defined in the past. Different browsers are free to implement event ordering however they see fit. While most are close enough for all practical purposes, there have been and continue to be some odd edge cases where browsers differ somewhat (and, of course, the many more cases where certain browsers fail to send certain events at all).
That said, the HTML 5 draft recommendation does make an attempt to specify how events will be queued and dispatched - the event loop:
To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section.
There must be at least one event loop per user agent, and at most one event loop per unit of related similar-origin browsing contexts.
An event loop has one or more task queues. A task queue is an ordered list of tasks [...] When a user agent is to queue a task, it must add the given task to one of the task queues of the relevant event loop. All the tasks from one particular task source must always be added to the same task queue, but tasks from different task sources may be placed in different task queues. [...]
[...]a user agent could have one task queue for mouse and key events (the user interaction task source), and another for everything else. The user agent could then give keyboard and mouse events preference over other tasks three quarters of the time, keeping the interface responsive but not starving other task queues, and never processing events from any one task source out of order. [...]
Note that last bit: it is up to the browser implementation to determine which events will be grouped together and processed in order, as well as the priority given to any particular type of event. Therefore, there's little reason to expect all browsers to dispatch all events in a fixed order, now or in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With