0

I am trying to detect a focus out event after focusin was set programatically. Take a look at the example: (click on blue element sets focusin, clicking on document should trigger focusout)

https://jsfiddle.net/k946vcza/1/

For some reason, if focusin is set with

  var focusin = new Event("focusin");
  red.dispatchEvent(focusin);

focusout does not get triggered when clicked on the document. If you first click on the red element and then on document, then focusout is detected as expected.

What am I missing here?

sanjihan
  • 5,592
  • 11
  • 54
  • 119

1 Answers1

0

focusin won't trigger the focus event (demonstrated in that the element doesn't get highlighted), and since focusout requires the element to be focused, you won't see it get called.

If you do something like setTimeout(()=>red.focus(), 0) instead of red.dispatchEvent(focusin), you will see the expected behaviour

Alberto Rivera
  • 3,652
  • 3
  • 19
  • 33
  • thanks man! this seems to work. I've got a small subquestion. Every time I set focus with focus() function, browser scrolling seems to jump up to the element who gained focus. Take a look: https://jsfiddle.net/k946vcza/2/ . Is it possible to cancel this behaviour? It happens even when the "about to be focused" element is visible in viewport. – sanjihan Jan 02 '18 at 20:11
  • Maybe this question helps? https://stackoverflow.com/questions/6740253/disable-scrolling-when-changing-focus-form-elements-ipad-web-app – Alberto Rivera Jan 02 '18 at 21:18