[JavaScript] Firing Order (Precedence) of Event Handler
There are two HTML elements, one is div element, and the other is input element. Assume that the focus is at input element in the beginning. onclick event handler of div element and onblur event handler of input element are registered. If div element is clicked, input element will lose focus. Here comes the question:
Which event handler is fired first?
onclick event handler of div element?
or onblur event handler of input element?
The answer is onblur event handler of input element is fired before onclick event handler of div element.
What if I want onblur event handler fired after onclick event handler?
This is a question similar to that asked in reference [1], and also the question I had when I developed my web application.
There are good news and bad news for the quesiton:
- The bad news is, according to references [2] and [3], the firing order (precedence) of event handlers are not defined in the HTML spec and hence depends on browser implementations.
- The good news is that although onblur event handler is fired before onclick event handler, onmousedown event handler is fired before onblur event handler. So we can move onclick event handler to onmousedown event of div element, which achieves the same result we need.
Summary
- Firing order (precedence) of event handlers depends on browser implementation. No spec on this.
- Register event handler to onmousedown event instead of onclick event, if you want the event handler to be fired before onblur event handler.
References:
[1] | jquery - How should I fire Javascript blur event after click event that causes the blur? - Stack Overflow |
[2] | What is the event precedence in JavaScript? - Stack Overflow |
[3] | Javascript event handler order - Stack Overflow |