0

I am confused by the value of document.activeElement during focus events. Consider the following example:

/*
 * 1. Click on button to focus it
 * 2. Press TAB
 */

const div = document.querySelector('div')
const add = div.addEventListener.bind(div)

add('keydown', () => console.log('Key down', document.activeElement), false)
add('keyup', () => console.log('Key up', document.activeElement), false)
add('focusout', () => console.log('Focus out', document.activeElement), false)
add('focusout', () => requestAnimationFrame(() => console.log('rAF Focus out', document.activeElement)), false)
<div>
  <button>Click</button>
  <input>
</div>

This results in:

Key down <button>Click</button>
Focus out <body>…</body>
rAF Focus out <input></input>
Key up <input></input>

Specifically i am wondering why document.activeElement is set to body in focusout?

spbks
  • 845
  • 3
  • 10
  • 18
  • Notice that by calling `add(…)` instead of `div.addEventListener(…)`, you are installing the event handlers on `window` not on that div element. – Bergi Nov 22 '19 at 09:07
  • oh, thanks, i didn't realize that – spbks Nov 22 '19 at 09:16
  • because focusout fires before the new focus, so at the that time, there is no true activeElement, the getter thus returns the default body. – Kaiido Nov 22 '19 at 09:24
  • so focus does not move directly to the next element in the tab order, but is first removed from the focused element, `blur` fires, and then focus moves to the next element? – spbks Nov 22 '19 at 09:49
  • 1
    Yes that's it. Sorry I miss time to dig the specs and write a comprehensive answer but that's indeed what happens. – Kaiido Nov 22 '19 at 10:07
  • Not sure if this is the correct spec, but i found the following for `blur`: "The focus MUST be taken from the element before the dispatch of this event type" - which supports your explanation. However, I'm unclear what this sentence for `focusout` means: "This event type MUST be dispatched before the element loses focus. [...] This event type is similar to blur, but is dispatched before focus is shifted" (see https://w3c.github.io/uievents/#event-type-focusout). Would that not suggest that the focused element in `focusout` is still the one that is about to lose focus? – spbks Nov 22 '19 at 13:53

0 Answers0