jQuery Tutorial Tutorials - jQuery .focus() method

jQuery .focus() method

The .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.

jQuery .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.

jQuery .focus() method Example

example

Set the username inputbox get the focus when the page is loaded.

$(document).ready(function(){
  $("#username").focus();
});

example

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();
});

Try now

Date:2019-08-29 19:08:55 From:www.Lautturi.com author:Lautturi