Focus event handler run in different order in IE than Firefox

I wanted to document a bit of an edge case browser incompatibility that I found: that event handlers aren’t always run in the same order in IE as they do in other browsers.

It’s a bit of a strange case where we were doing something not entirely sensible. :) There was an input box which had a click event and a blur event hooked up as inline event handlers. During the input box’s click event, another element on the page was given focus which caused the input’s blur event to run.

The code for it looked something like this:

  1. var input1 = document.getElementById("input1");
  2. input1.onclick = function(e)
  3. {
  4.     debug.write("Before change focus");
  5.     document.getElementById("button").focus();
  6.     debug.write("After change focus");
  7. };
  8.  
  9. input1.onblur = function(e)
  10. {
  11.     debug.write("Lost focus event fired");
  12. };

Complete example

In IE, the blur event doesn’t run until after the click event has completely finished running. It’s like the event just gets added to the end of a queue somewhere. In Firefox (and other browsers), the blur event gets run straight away. It runs as soon as the focus() method is called and then the click event continues running.

So if you run the code above in IE the output is:

Before change focus
After change focus
Got focus event fired

In Firefox the output is:

Before change focus
Got focus event fired
After change focus

What this affects

This happened using inline events and attachEvent (thought that might be a work around). I tested in Firefox, Opera and Safari. They all worked the same way. IE was the only one to be different (I mention this for informational purposes – not to judge ;)).

An interesting thing is how this affected IE’s proprietary document.activeElement property. The activeElement property gets changed as soon as the focus() method is called even though the blur event isn’t fired until later.

It seems to only affect focus related events. I could reproduce the behaviour with the focus and blur events but when I tried the same with a click event, IE fired the events in the same order as all the other browsers. I couldn’t think of any other events to trigger programmatically to test the theory further.

I’m afraid I didn’t find a workaround for this. I’d love to know about one if someone else has found one.

Posted on 16 Jan 08 by Helen Emerson (last updated on 16 Jan 08).
Filed under Browser quirks