jQuery enables it like so:
$( "input" ).triggerHandler( "focus" );
How can I achieve the same without jQuery?
jQuery enables it like so:
$( "input" ).triggerHandler( "focus" );
How can I achieve the same without jQuery?
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).
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