JavaScript FocusOut - get the element that receives focus

Peter M. picture Peter M. · Apr 5, 2014 · Viewed 10.3k times · Source

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:

Answer

valadil picture valadil · May 19, 2014

I have a hypothesis and workaround for firefox. document.activeElement seems to work. Then focusout hits, so it gets removed. By the time focusin hits (or maybe immediately after) there will be a focused element again. But between out and in there is nothing focused, so no element is being reported as active.

My workaround is a stupid setTimeout hack. setTimeout( function() {console.log(document.activeElement)}, 1); reliably gets me an active element. Granted I've only tested in one machine and spent all of 90 seconds doing so, but it's the best I've found so far.