.focus() methodThe .focus() method in jQuery is used to run a function when the matched elements have the focus.
It also used to trigger an focus event on an element.
.focus() method Syntax.focus() .focus(handler) .focus(eventData,handler)
| Parameter | Type | Description |
|---|---|---|
handler |
Function | A function to execute when the focus is triggered on the matched element. |
eventData |
Anything | Additional data passed to the event handler. |
.focus() method ExampleSet the username inputbox get the focus when the page is loaded.
$(document).ready(function(){
$("#username").focus();
});
When the input fields get the focus, execute the event handle function.
When user click the button,Trigger an focus event on the input elemetns.
HTML
<form> <input type="text" name="username"> <input type="text" name="email"> </form> <button>Trigger focus event</button>
$( "input" ).focus(function() {
console.log("The input box "+$(this).val() +" gets the focus! ")
console.log("Handler for .focus() called.");
});
$('button').click(function(){
$( "input" ).focus();
});
