Search code examples
javascriptfocusout

JavaScript FocusOut - get the element that receives focus


When the FocusOut event is raised, how do you know which element receives the focus?

The correct way seems to be to use the event's relatedTarget property. However, this seems not to work in all browsers:

  • in Google Chrome, it works
  • in Firefox and Internet Explorer, the relatedTarget is null
  • in Safari, the relatedTarget property doesn't even exist

I have found a workaround which works only in IE (using document.activeElement), but I'm wondering if there isn't a general solution that has proven to work in all major browsers.

Although I can find similar questions and answers, I haven't found any solution which really works in all browsers.

EDIT: the example below shows what I mean.

Code:

document.getElementById('text1').addEventListener('focusout', function(e) {
  // At this point, I want to know which element is receiving the focus (i.e. text2)
  console.log(e.relatedTarget); // works in Chrome
  console.log(document.activeElement); // works in IE
  // both do not work in Firefox or Safari
});
<input id="text1" type="text" value="first" />
<input id="text2" type="text" value="second" />


Solution

  • As you hinted at, FocusEvents come with a relatedTarget property which, for focusout events, points at the element that is about to receive focus (at the next tick of the event loop). As of 2024, this property seems to be supported by all major browsers, see: https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/relatedTarget