3

jQuery enables it like so:

$( "input" ).triggerHandler( "focus" );

How can I achieve the same without jQuery?

https://api.jquery.com/triggerHandler/

Viktor Sec
  • 2,756
  • 1
  • 24
  • 31
  • Possible duplicate of [How to find event listeners on a DOM node when debugging or from the JavaScript code?](https://stackoverflow.com/questions/446892/how-to-find-event-listeners-on-a-dom-node-when-debugging-or-from-the-javascript) - second answer and below I think. – kabanus Mar 15 '19 at 15:43

2 Answers2

4

You use dispatchEvent on the element for which you want focus to be triggered. See the docs and an example here.

const event = new FocusEvent('focus', {
  view: window,
  bubbles: true,
  cancelable: true
});

const myInput = document.getElementById('myInput');

myInput.dispatchEvent(event);
#myInput:focus {
  background: red;
}
<input id="myInput" type="text" onfocus="console.log('Input focused!');"/>

As you can see in the above code, the console.log statement is run based on the bound event to the input tag, but the element is not actually focused (because otherwise the input box would be red, which you can try by clicking on it).

Tim Klein
  • 2,538
  • 15
  • 19
  • Thank you, this is exactly what I asked for. Unfortunately, it still focuses the input on my side. (I want to trigger internal functionality of a 3rd party component.) Your example clearly works, so the problem is somewhere else. – Viktor Sec Mar 15 '19 at 16:03
  • Cheers, any other insight into the problem? I'd be happy to help – Tim Klein Mar 15 '19 at 17:17
1

Use the getEventListeners(node) function

In your case: console.log(getEventListeners(document.getElementsByTagName('input')[0]));

You will get all the listeners, then you can filter those that are attached to the focus event

Sergej
  • 2,030
  • 1
  • 18
  • 28
  • 1
    Please note this is a browser specific command, though for all I know edge may have started including it as well. – kabanus Mar 15 '19 at 15:45