Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

jQuery focus() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The jQuery focus() is an inbuilt method 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. 

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

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

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        span {
            display: none;
        }
  
        body {
            width: 35%;
            height: 50px;
            border: 2px solid green;
            padding: 35px;
            margin: 10px;
        }
    </style>
    <script src=
    </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(function () {
            $(this).next("span").css("display", "inline");
        });
    </script>
</body>
  
</html>


Output: 

 

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

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        span {
            display: none;
        }
  
        body {
            width: 30%;
            height: 50px;
            border: 2px solid green;
            padding: 35px;
            margin: 10px;
        }
    </style>
    <script src=
    </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>


Output: 

 


My Personal Notes arrow_drop_up
Last Updated : 18 Nov, 2022
Like Article
Save Article
Similar Reads