jQuery | focus() with Examples

The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button.
Syntax:

$(selector).focus(function)

Here selector is the selected element.
Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.
Return Value: It returns the selected element which get focused.

jQuery code to show the working of focus() method:

Code #1:
In the below code, a function is passed to this method.



filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
    <style>
        span {
            display: none;
        }
          
        body {
            width: 35%;
            height: 50px;
            border: 2px solid green;
            padding: 35px;
            margin: 10px;
        }
    </style>
    </script>
</head>
  
<body>
    <!-- this paragraph element get focused -->
    <p>
        <input type="text"> <span>focused</span></p>
  
    <!-- jQuery cdee to show working of this method -->
    <script>
        $("input").focus(function() {
            $(this).next("span").css("display", "inline");
        });
    </script>
  
</body>
  
</html>

chevron_right


Output:
Before the mouse clicking inside of the input field-

After the mouse clicking inside of the input field with text “GeeksforGeeks”-

Code #2:
In the below code, no parameter is passed to this method.

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
    <style>
        span {
            display: none;
        }
          
        body {
            width: 30%;
            height: 50px;
            border: 2px solid green;
            padding: 35px;
            margin: 10px;
        }
    </style>
    </script>
</head>
  
<body>
    <!-- this paragraph element get focused -->
    <p>
        <input type="text"> <span>focused</span></p>
  
    <!-- jQuery code to show working of this method -->
    <script>
        $("input").focus();
    </script>
  
</body>
  
</html>

chevron_right


Output:
Before the mouse is clicked inside of the input field-

After the mouse is clicked inside of the input field with text “GeeksforGeeks”-



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.