3

[JavaScript] Firing Order (Precedence) of Event Handler

 2 years ago
source link: http://siongui.github.io/2012/10/03/javascript-firing-order-precedence-of-event-handler/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[JavaScript] Firing Order (Precedence) of Event Handler

Updated: March 03, 2015

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.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK