Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" />
like image 221
Peter M. Avatar asked Apr 05 '14 10:04

Peter M.


1 Answers

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.

like image 151
valadil Avatar answered Nov 09 '22 16:11

valadil