Search code examples
javascripthtml

If I click a link directly from a textfield, does onblur consistently fire before the link?


I have a text input and a link used as a button set up on my website like so:

<input type="text" onblur="blurfunction()">
<a href="javascript:buttonfunction()">Button</a>

It's important for my functionality to have blurfunction() always fire before buttonfunction(), even if the link is clicked directly without exiting the text field. From my limited testing in latest Chrome and Firefox clicking on the link directly from the text field consistently deselects the text field and fires blurfunction() before handling the link click and firing buttonfunction().

The specification for the blur event type specifies:

The focus MUST be taken from the element before the dispatch of this event type.

The specification for the focus event type specifies:

The focus MUST be given to the element before the dispatch of this event type.

While the specification for each individual event is pretty clear on the order things are handled for each element separately, I'm not sure if there's anything in here that specifically states that the blur event gets dispatched before the focus is given to the next element.

Can I expect this behaviour to be consistent across all browsers/devices? Is the order these calls happen defined in the HTML/JavaScript spec or could implementations differ between browsers?


Solution

  • I believe the events should be in the order you expect.

    When you click on the link, the first event that occurs is mousedown. The specification says that the focusing steps are run at the target of the mousedown. If you then read the specification of focus update steps, this step includes triggering the change and blur events on the input element.

    The link isn't followed until you finish clicking on the link, which is after the mouseup.