'How to fire a focusin event in a crossbrowser way?
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | maburdi94 |