The jQuery focusin 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.
$("input").focusin(function(){
//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 focusin() method.
Once the user clicks on the input field, the focusin() method will be triggered, and we can change its background color.
$("#fname").focusin(function(){
$("#fname").css('background','green');
});
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#fname").focusin(function(){
jQuery("#fname").css('background','green');
});
This can also be done using the jQuery focus() method.
An Interactive Example of the jQuery focusin() 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:
$("#fname").focusin(function(){
$("#fname").css('background','#d1e2f3');
});
$("#fname").focusout(function(){
$("#fname").css('background','#fff');
});
The final code and output for this example of using the jQuery focusin() method is below:
Code Output:
Full Code:
<script>
$("#fname").focusin(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 focusin() method.