How to fire a focusin event in a crossbrowser way?

509 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.