jQuery focus() method attaches an event handler function to html elements. This event handler function executes when a form field gets focus.
jQuery focus() method Syntax
$("input").focus(function(){ //code to execute when the focus event is triggered });
jQuery focus() Example
In the following example we have two input form fields, we want to change the background colour of the form field when the field gets focus (when we click inside the box), to do this, we have attached the event handler function where we are changing the background colour of html elements, to the input html element. This way when any of the form field gets focus, its background colour gets changed to colour value #444.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("input").focus(function(){ $(this).css("background-color", "#444"); }); }); </script> </head> <body> <h2>jQuery focus event example on Beginnersbook.com</h2> Your Name: <input type="text" name="name"><br> Your Age: <input type="text" name="age"> </body> </html>
Output:
Before any form field gets focus:
This screenshot is taken when the html page is initially loaded and we have not clicked on any form field:
After the first form field gets focus:
This screenshot is taken after we have clicked inside first form field, the form field gets focus so its background colour is changed to #444 as set in the event handler function.
Leave a Reply