10

Apparently IE (11) has an issue with relatedTarget, for example on blur events. Is there an alternative for IE to get the relatedTarget?

Here is an example that produces an error in IE: https://jsfiddle.net/rnyqy78m/

Daniel
  • 3,383
  • 4
  • 30
  • 61

2 Answers2

27

It looks like IE11 sets document.activeElement to the next focused element before the blur event is called. So to handle blur correctly in all browsers including IE11 you could use something like

var target = evt.relatedTarget;
if (target === null) { target = document.activeElement; }

I adapted your fiddle to use this: https://jsfiddle.net/hukt0rhj/

christiansabor
  • 321
  • 1
  • 3
  • 5
14

If I look at this list: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget blur isn't included as having a standard secondary target. So I assume the secondary target on blur in chrome is non-standard.

If you replace blur by focusin or focusout, it also works for IE11 for me.

Shilly
  • 8,511
  • 1
  • 18
  • 24
  • Thanks. I have only been using `blur` so far. But I guess that is because I am using Firefox and the doc you linked to states that Firefox does not support the `focusout` `relatedTarget`.... – Daniel Dec 23 '16 at 09:57
  • I hope to get an answer how to get it work across browsers here: http://stackoverflow.com/q/41299372/1981832 – Daniel Dec 23 '16 at 10:13
  • You could try feature detection. I don't have an up-to-date firefox atm, but try something like: `var eventName = MouseEvent.prototype.hasOwnProperty('relatedTarget') ? 'focusout' : 'blur';` Although I have no idea if firefox will return 'false' here. The idea is that you just check which one you can use before binding the event listener. You couldcheck the navigator, but that sounds more complex. – Shilly Dec 23 '16 at 10:19
  • You could use [currentTarget](https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget) in IE. – R. Oosterholt Jan 29 '18 at 16:09
  • 1
    Swapping out 'blur' for 'focusout' and 'focus' for 'focusin' solved it for me. Thanks! – MorganR Jun 27 '18 at 09:56