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?
Definition and Usage The onfocus event occurs when an element gets focus.
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.
The focus event fires when an element has received focus. The event does not bubble, but the related focusin event that follows does bubble. The opposite of focus is the blur event, which fires when the element has lost focus. The focus event is not cancelable.
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:
And to use it:
var 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.
Yes it is possible using element.focus()
document.getElementById("textBox").focus();
function myFunction(x) {
x.style.background = "yellow";
}
function focusText() {
document.getElementById("textBox").focus();
}
Enter your name: <input type="text" id="textBox" onfocus="myFunction(this)">
<p>When the input field gets focus, a function is triggered which changes the background-color.</p>
<button onclick="focusText()">Focus the Textbox</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With