jQuery focus() Method

Last Updated:

jQuery focus() Method

The jQuery focus() method is used for the following 2 purpose

  1. To run a callback when a specified element is focused.
  2. To trigger the focus event of a specified element.

Run a Callback

In the following example, we will run a callback function when an input get focus.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery focus() Method</h1> <p>Focus the input.</p> <input type="text"> <script> $(document).ready(function(){ $("input").focus(function(){ $(this).val("Input is focused"); }); }); </script> </body> </html>

Syntax

$(selector).focus(callback);

Parameter Values

ValueTypeExplanation
callback Optional Specifies a function to be called once the input is focused.

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
focus()YesYesYesYesYesYesYesYesYesYesYesYesYes

Trigger a focus Event

In the following example, we will trigger a focus event when a button is clicked.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery focus() Method</h1> <p>Focus the input, or click on the button.</p> <input type="text"> <button>Trigger focus Event</button> <script> $(document).ready(function(){ $("input").focus(function(){ $(this).val("Input is focused"); }); $("button").click(function(){ $("input").focus(); }); }); </script> </body> </html>

Share this Page

Meet the Author