Open In App

jQuery focus() Method

Last Updated : 14 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

jQuery focus() is an inbuilt method that is used to focus on an element. The element gets 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 in the form of a callback function which will be called once the focus event occurs.

Example 1: The below example explains the focus() method with a callback function passed to it.

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 example, the focus() method is invoked without any parameters.

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: 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads