3

I've found very hard to manually trigger a focusin event using just Javascript (no jQuery) for it for a test suite.

Apparently when the browser does not have the focus (that can happen only in tests) I want to simulate the focusin event myself.

I've found that the CustomEvent constructor works

var event = new CustomEvent('focusin', { bubbles: true, cancelable: false });
this.dispatchEvent(event);

but I need to make this IE9+. The old-fashioned way doesn't seems to work.

var event = document.createEvent('Event');
event.initEvent('focusin', true, false);
this.dispatchEvent(event);

AFAIK those two constructions should be equivalent in functionality, but clearly that's not true. Tested in Chrome/Firefox/Safari when the browser's window doesn't have the focus.

Is there something wrong in the second snippet?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
miguel.camba
  • 1,777
  • 1
  • 14
  • 19

1 Answers1

0

You can do this if the element has children by calling focus() on the firstElementChild.

let el = document.getElementById('myDivId');
el.firstElementChild.focus();

This will trigger focusin on the div and bubble up to any of the div's parents.

maburdi94
  • 41
  • 2