jQuery Event focus() Method



The jQuery event focus()  method is used to attach an event handler to the focus event or trigger that event on the selected element. The focus event occurs when an element gets focus, either from a mouse click or by navigating through the tab.

Syntax

Following is the syntax of the jQuery event focus() method −

$(selector).focus(function)

Parameters

This method accepts an optional parameter as a function, which is described below −

  • function − An optional function to execute when the focus event occurs.

Return Value

This method does not have a return value.

Example 1

The following program demonstrates the usage of the jQuery event focus() method −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Click on the below button to highlight this text.</p>
    <button>Focus on above text</button>
    <script>
        $('button').focus(function(){
            $('p').css("color", "red");
        });
    </script>
</body>
</html>

Output

The above program displays a message and a button. When the button is clicked, the text color changes to "red" −


When a user clicks on the displayed button −


Example 2

Highlight an input field when it gets focus.

The following is another example of the jQuery event focus() method. We use this method to focus on an input field −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Click on the below input field to get focused.</p>
    <label for="">Enter your name: </label>
    <input type="text" placeholder="Name">
    <script>
        $('input').focus(function(){
            $(this).css({"background-color":"green", "color":"white"});
        });
    </script>
</body>
</html>

Output

After executing the program, an input field will be displayed. When the user clicks on this input field, it will gain focus −


When a user clicks on an input field −


Example 3

Use the focus() method without the function parameter.

In the example below, we use the jQuery focus()  event method without specifying a function. When the program is executed, an input field will automatically get focused −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    input{
        width: 200px;
        padding: 10px 10px;
    }
</style>
</head>
<body>
    <label for="">Enter your name: </label>
    <input type="text" placeholder="Name">
    <script>
      $('input').focus();
    </script>
</body>
</html>

Output

Once the above program is executed, it displays a focused input field −


jquery_ref_events.htm
Advertisements