Related Articles

Related Articles

How to get focused element using jQuery?
  • Last Updated : 16 Oct, 2019

To focus on element there is an inbuilt selector available in jQuery, which is used to detect the currently focused element. When the element is get focused by the mouse click or by the tab-navigating button this selector return the selected element. You can add the element in JQuery to focused that element easily. Here we will use the JQuery inbuilt selector $(“:focus”)

Syntax:

$(":focus")

Example 1: This example shows how to focus an element using jQuery.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to get focused element
        using jQuery?
    </title>
      
    <script src=
    </script>
      
    <script>
        $(document).ready(function() {
            $("input").focus();
            $(":focus").css("background-color", "yellow");
        });
    </script>
      
    <style>
        .geeks {
            width: 350px;
            height: 100px;
            border: 2px solid green;
            padding-bottom: 15px;
            margin: 10px;
        }
        h1 {
            color:green;
        }
    </style>
</head>
  
<body>
    <center>
        <div class="geeks">
            <h1>GeeksforGeeks</h1>
            <input type="text" placeholder="Focused Input" />
        </div>
    </center>
</body>
  
</html>                    

chevron_right


Output:

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    
<head>
    <title>
        How to get focused element
        using jQuery?
    </title>
      
    <script src=
    </script>
      
    <script>
        $(document).ready(function(){
            $("input").focus();
            $(":focus").css("background-color", "red");
            $("button").focus();
            $(":focus").css("background-color", "green");
        });
    </script>
      
    <style>
         .geeks {
            width: 350px;
            height: 100px;
            border: 2px solid green;
            padding-bottom: 15px;
            margin: 10px;
        }
        h1 {
            color:green;
        }
    </style>
</head>
    
<body>
    <center>
        <div class="geeks">
            <h1>GeeksforGeeks</h1>
            <input type="text" placeholder="Focused Input" />
            <button type="button" >
                <a href="https://ide.geeksforgeeks.org/tryit.php">
                    Click me visit ide
                </a>
            </button>
        </div>
    </center>
</body>
    
</html>

chevron_right


Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :