javascriptbuttontextfieldonbluronmouseup

JavaScript event handler race


If I have a text field with a registered onblur event handler and a button with a registered onmouseup event handler, which one of those two functions will run sooner and why?

To make my question clearer, let's suppose the focus is currently on the text field and I want to click on the button.

Will there be any difference between various Internet browsers?

Edit

Especially tricky seems the onmousedown event when it's registered with the button, whilst the text field has an onblur event registered with it.


Solution

  • The spec says blur must be fired when focus leaves the element (after taking focus away), but I don't see any explicit statement about when that must occur relative to the event causing the focus to be moved away.

    Certainly the mouseup will happen much later (in computer terms), as first you have to mousedown.

    I would have expected blur to fire prior to even the mousedown, but I would have been wrong: According to experimentation, mouseup is after, but mousedown is before. I tested that using Chrome 26, Opera 12.15, Firefox 20, IE8, and IE9 — and if you can get those five to agree on a behavior, it's likely to be consistent in others... :-) My suspicion is that this is because if you prevent the default action of the mousedown, focus never moves away from the text field: Example. (This behavior is consistent across four of those five browsers, with IE8 not preventing the focus change — meaning IE7 and 6 probably don't, either.) So while it seems odd, it does kind of make sense.

    As always, test with the browsers you intend to support.