Skip to content

Instantly share code, notes, and snippets.

@rodneyrehm
Created April 20, 2015 20:56
Show Gist options
  • Save rodneyrehm/46e03d6e077257daa04c to your computer and use it in GitHub Desktop.
Save rodneyrehm/46e03d6e077257daa04c to your computer and use it in GitHub Desktop.
Excerpt of the focus events chapter of my upcoming article-series/ebook on focus in general

The following is largely based on these test results


According to DOM Level 3 Focus Event Order there is a whole slew of events to be dispatched upon change of focus. focusin and focus are the two events dispatched the first time any element of the document receives focus. After that, when focus shifts to another element, we first get focusout on the element that has focus, then focusin on the element that will receive focus, then blur on the element that just lost focus, then focus on the element that got focus.

[…]

While focusout and focusin sound like the superior choice, they are not supported in Gecko at all. Blink 449857, WebKit 140596, Trident 1092647 mess up the order: blur, focusout, focus, focusin. And as far as I can see there is no way to polyfill these events properly, either. Only IE11 seems to get the order correct, but that may be due to the a/synchronous bug explained later.

[…]

So far Trident looks like the engine getting the most things right - but fear not, here's a fun one for you. DOM Level 3 Events declare all FocusEvents to be executed synchronously. That means, that the following code should print hello world:

var element = document.getElementById('#gustav');
element.addEventListener('focus', function() {
  console.log('hello');
}, true);

element.focus();
console.log('world');

All engines execute FocusEvents synchronously and thus print hello world except for IE11, where the console will read world hello. In Spartan all focus events are dispatched synchronously, which is why I didn't file a bug for this.

@rodneyrehm
Copy link
Author

With Internet Explorer Team closing the issue with WONTFIX, I'm left wondering what focusin and focusout bring to the table that blur and focus cannot - other than bubbling, which really is no biggie once you realized the event delegation can also be done in the capture phase.

I am interested in feedback. Why are you using focusin and focusout?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment