skip to Main Content

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?

2

Answers


  1. It’s hard to say if it will be consistent between ALL browsers, especially with the weirdness that can happen with the touch interface on mobile devices.

    There are dozens of different browsers and hundreds/thousands of versions between them. It’s hard to say definitively whether the same Bubbling/DOM propagation would work the same. If you go by the JavaScript spec with DOM event bubbling and utilize the correct event listeners it should work. However, the only way I’m aware of to be 100% sure would be to call the blurFunction in your code for the buttonFunction.

    function buttonFunction (){
        blurFunction()
    }
    

    Also, would recommend using a semantic <button onclick=""></button> for your code instead of styling a <a href="" />

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search