How to get focused element using jQuery?
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.
<!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> |
Output:

Example 2:
<!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" > Click me visit ide </a> </button> </div> </center> </body> </html> |
Output:

Recommended Posts:
- How to remove parent element except its child element using jQuery ?
- jQuery | Move an element into another element
- How to change the element id using jQuery ?
- jQuery | Create a div element
- How to create a div element in jQuery ?
- jQuery | element + next Selector
- jQuery | element Selector
- How to select an element by name with jQuery?
- How to check if an element is hidden in jQuery?
- Get the height of the hidden element in jQuery
- How to change an HTML element name using jQuery ?
- How to check an element has certain CSS style using jQuery ?
- How to check an element is visible or not using jQuery?
- How to check an element contains a class using jQuery?
- jQuery | element ~ siblings Selector
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.
Improved By : nidhi_biet



