Reputation: 441
How to trigger focus event on a textbox using javascript?
For example in jQuery we can trigger the focus event with $('#textBox').focus()
.
Likewise do we have any similar trigger functionality in pure javascript?
Upvotes: 13
Views: 39126
Reputation: 18783
I had to fiddle with this finally, and came up with something that seems to work cross browser:
function triggerFocus(element) {
let eventType = "onfocusin" in element ? "focusin" : "focus";
let bubbles = "onfocusin" in element;
let event;
if ("createEvent" in document) {
event = document.createEvent("Event");
event.initEvent(eventType, bubbles, true);
}
else if ("Event" in window) {
event = new Event(eventType, { bubbles: bubbles, cancelable: true });
}
element.focus();
element.dispatchEvent(event);
}
It takes into account that some browsers support focusin
events, and some only support focus
events. It sets focus using the native focus
function, and then dispatches a "focusin" event or "focus" event, depending on which the browser supports.
Tested in:
And to use it:
let foo = document.getElementById("foo");
triggerFocus(foo);
This is universal and should work with any element that can receive focus.
Update #1
The jQuery focus()
function will not trigger native focus handlers. I hit a bit of snag when mixing native focus handlers attached via HTMLElement.addEventListener(...)
and focus event handlers attached via jQuery. While jQuery.focus()
will trigger handlers attached using addEventListener()
, the dispatchEvent()
function will not trigger event handlers attached via $("...").focus(event => { ... })
. Just bear that in mind if you use this solution.
Upvotes: 20
Reputation: 5847
Quite simple: Element.focus()
This will not trigger the onfocus event See Greg's answer if that is a requirement.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
Upvotes: -1