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:
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" />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With