jQuery :focus Selector
The :focus selector is used to select the element that currently has focus. The term "Focus" refers to the element that is currently receiving input from the keyboard or other input device. We can apply "Focus" to form elements like <input>, <textarea>, <button>, etc.
Syntax
Following is the syntax of jQuery :focus selector −
$(":focus")
Parameters
The :focus selector selects the currently focused element.
Example 1
In the following example, we are using the jQuery :focus selector to select the element that currently has focus −
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input").focus(function(){
$(this).css("background-color", "yellow");
}).blur(function(){
$(this).css("background-color", "");
});
});
</script>
</head>
<body>
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your name">
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email">
</form>
</body>
</html>
After executing the above program, click on the input text fields. The currently focused element will be highlighted with yellow background color.
Example 2
In this example, we are applying a blue border to a textarea when it gains focus and removes the border when it loses focus −
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("textarea").focus(function(){
$(this).css("border", "2px solid blue");
}).blur(function(){
$(this).css("border", "");
});
});
</script>
</head>
<body>
<form>
<label for="message">Message:</label>
<textarea id="message" name="message" placeholder="Enter your message"></textarea>
</form>
</body>
</html>
Execute the above program and click on the textarea to see the blue border.
jquery_ref_selectors.htm