how to trigger focus event on a textbox using javascript?

Ajay Gangisetti picture Ajay Gangisetti · May 21, 2015 · Viewed 19.7k times · Source

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?

Answer

Greg Burghardt picture Greg Burghardt · Sep 21, 2018

I had to fiddle with this finally, and came up with something that seems to work cross browser:

function triggerFocus(element) {
    var eventType = "onfocusin" in element ? "focusin" : "focus",
        bubbles = "onfocusin" in element,
        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:

  • Firefox 62
  • Chrome 69
  • Internet Explorer 11 (yeah, yeah. I know. We have to support it at work, though)
  • Microsoft Edge 15

And to use it:

var foo = document.getElementById("foo");

triggerFocus(foo);

This is universal and should work with any element that can receive focus.