The jQuery focus method will occur when an element (most of the time an input) gets the user’s focus. This occurs when either the user mouse clicks onto the element, or tabs onto it using the keyboard.

  //do something

Let’s say we have the following HTML:

To highlight the input field when the user clicks on it, we can use the jQuery focus() method.

Once the user clicks on the input field, the focus() method will be triggered, and we can change its background color.


If you are using WordPress, don’t forget to change the $ to jQuery as below:


This can also be done using the jQuery focusin() method.

An Interactive Example of the jQuery focus() Method

Below we will set up a simple form with a name field and a submit button.

Here is the HTML code:

When the user clicks or tabs into the name field, we will change the background color to light blue. When they click away, we will use the focusout() method to reset the background.

Here is the code JavaScript code:



The final code and output for this example of using the jQuery focus() method is below:

Code Output:

Full Code:

<script> $("#fname").focus(function(){ $("#fname").css('background','#d1e2f3'); }); $("#fname").focusout(function(){ $("#fname").css('background','#fff'); }); </script>

Hopefully this article has been useful to help you understand how to use the jQuery focus() method.

Categorized in:


Last Update: March 20, 2024